思維導(dǎo)圖
例子
- 1.模擬do...while功能
int i = 0;
for (System.out.println('a'), System.out.println('b');
i < 3;
i++, System.out.println('c')) {
if (i == 2) continue;
System.out.println('d');
}
int a = 5, b = 10;
boolean flag = true;
// 模擬do...while功能
while (flag || a > b) {
flag = false;
}
- 方法 傳入一個數(shù)組 和 一個元素 找到是否有 找到返回這個元素在數(shù)組哪個位置 沒有 返回 -1
冒泡排序
public static void bubbleSort(int[] x) {
boolean swapped = true;
for (int i = 1; swapped && i < x.length; i++) {
swapped = false;
for (int j = 0; j < x.length - i; j++) {
if (x[j] > x[j + 1]) {
int temp = x[j + 1];
x[j + 1] = x[j];
x[j] = temp;
swapped = true;
}
}
}
}
public static int search(int[] x, int k) {
for (int i = 0; i < x.length; i++) {
if (x[i] == k) {
return k;
}
}
return -1;
}
public static void main(String[] args) {
int[] array = new int[40];
for (int i = 0, len = array.length; i < len; i++) {
array[i] = (int) (Math.random() * 100);
}
System.out.println(Arrays.toString(array));
// System.out.println(search(array, 25));
// System.out.println(search(array, 62));
bubbleSort(array);
System.out.println(Arrays.toString(array));
}
- 3.輸入正整數(shù) 算每位數(shù)字相加和
Scanner input = new Scanner(System.in);
System.out.print("輸入正整數(shù): ");
int n = input.nextInt();
int sum = 0;
while (n > 0) {
/*int temp = n;
temp %= 10;
n /= 10;
sum += temp;*/
sum += n % 10;
n /= 10;
}
System.out.println(sum);
input.close();
- 4.階乘和求和
public static int sum(int n) {
if (n == 1) {
return 1;
}
return n + sum(n - 1);
}
public static double f(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * f(n - 1);
}
public static void main(String[] args) {
System.out.println(f(5));
System.out.println(sum(5));
}
- 5. 有個小孩上樓梯 10級
1次走可以 1級樓梯悯舟、2級樓梯、3級樓梯
有多少走法
public static int steps(int n) {
if (n < 0) {
return 0;
}
else if (n == 0) {
return 1;
}
return steps(n - 1) + steps(n- 2) + steps(n - 3);
}
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(steps(i));
}
}
- 6.游戲里有三根金剛石柱子,在一根柱子上從下往上安大小順序摞著64片黃金圓盤伺通。玩家需要做的是把圓盤從下面開始按大小順序重新擺放在另一根柱子上蹄皱。并且規(guī)定等孵,在小圓盤上不能放大圓盤辈赋,在三根柱子之間一次只能移動一個圓盤袋哼。
n^3 - 1
把n-1盤子搬到c
把最大的盤子搬到b
把n-1盤子搬到b
輸出步驟
public static void hanoi(int n, char a, char b, char c) {
if (n > 0) {
hanoi(n - 1, a, c, b);
System.out.println(a + "--->" + b);
hanoi(n - 1, c, b, a);
}
}
public static void main(String[] args) {
hanoi(3, 'A', 'B', 'C');
}
作業(yè)
- 1.輸入正整數(shù) 分解質(zhì)因子
4 -> 2 2
6 -> 2 3
12 -> 2 2 3
60 -> 2 2 3 5
25 -> 5 5
Scanner input = new Scanner(System.in);
System.out.print("請輸入一個正整數(shù): ");
int n = input.nextInt();
for (int i = n / 2; i > 1; i--) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
while (n % i == 0) {
n /= i;
System.out.println(i);
}
}
}
input.close();
}
2.數(shù)字全排列
3.隨機(jī)生成 1010 的迷宮
左上角入口 右下角出口
求多少走法*