java基础算法(不定时更新)

/**
	 * 100米绳子,对折6次,求其长度
	 */
	public static void ropeOne() {
		double rope = 100;
		for (int i = 1; i <= 6; i++) {
			rope = rope / 2;
			System.out.println("第" + i + "次对折后,绳子的长度为" + rope);
			if (i == 6) {
				System.out.println("对折6次后绳子的长度为  = " + rope);
			}
		}
	}

	/**
	 * 3000米绳子,每天减少一半,多少天后小于5米
	 */
	public static void ropeTwo() {
		double rope = 3000;
		int count = 0;
		// 第一种做法简单
		while (rope > 5) {
			rope = rope / 2;
			count++;
		}
		System.out.println("第" + count + "天后,绳子小于5米");
		// 第二种做法,复杂
		while (true) {
			rope = rope / 2;
			count++;
			System.out.println("第" + count + "天后,绳子长度 = " + rope);
			if (rope <= 5) {
				System.out.println("第" + count + "天后,绳子小于5米");
				break;
			}

		}
	}

	/**
	 * 1+2+3...+n
	 */
	public static void num(int n) {
		int count = 0;
		for (int i = 1; i <= n; i++) {
			count += i;
			if (i == n) {
				System.out.println("总数为:" + count);
			}

		}
	}

	/**
	 * 1,2,3,4个数有多少种不同组合
	 */
	public static void total() {
		int a = 0;
		for (int i = 1; i <= 4; i++) {
			for (int j = 1; j <= 4; j++) {
				for (int k = 1; k <= 4; k++) {
					for (int n = 1; n <= 4; n++) {
						if (i != j && j != k && k != i) {
							a++;
						}
					}
				}
			}
		}
		System.out.println("总有" + a);
	}

	/**
	 * 冒泡排序
	 */
	public static void demo() {
		int temp;
		int[] arr = new int[] { 9, 1, 6, 4, 135, 8 };
		for (int i = 0; i < arr.length - 1; i++) {
			for (int j = 0; j < arr.length - i - 1; j++) {
				if (arr[j] > arr[j + 1]) {
					temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;

				}
			}
		}
		System.out.println("arr = " + Arrays.toString(arr));
	}

	/**
	 * 字符串反转 1.charAT()方法
	 */
	public static void StringStrOne(String s) {
		int lenth = s.length();
		String resultStr = "";
		for (int i = 0; i < lenth; i++) {
			resultStr = s.charAt(i) + resultStr;
		}
		System.out.println("反转后的字符串为:" + resultStr);
	}

	/**
	 * 字符串反转 2.charAT()方法
	 */
	public static void StringStrTwo(String s) {
		StringBuffer sb = new StringBuffer(s);
		System.out.println("反转后的字符串为:" + sb.reverse().toString());
	}

	/**
	 * 字符串反转 3.利用 String 的 toCharArray 方法先将字符串转化为 char 类型数组,然后将各个字符进行重新拼接:
	 */
	public static void StringStrThree(String s) {
		char[] c = s.toCharArray();
		String str = "";
		for (int i = 0; i < c.length; i++) {
			str = c.toString() + str;
		}
		System.out.println("反转后的字符串为:" + str);
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值