Java 练习(三)

  1. 从键盘输入一个n,代表二维数组的行和列,依次读入n行由空格和数字字符组成的字符串,将字符串中的每个数字字符转换成整形数据,存成二维数组的一行,如果输入的数字字符数目少于n个,以0补足,如果超过n个,截取前n位。
 1example:
 2
 3input:
 45
 53 2 1 7 6 8
 611 2 4 12 5
 74 3 1
 87 6 5
 91
10
11output:
12[[3, 2, 1, 7, 6], [11, 2, 4, 12, 5], [4, 3, 1, 0, 0], [7, 6, 5, 0, 0], [1, 0, 0, 0, 0]]
 1import java.util.Scanner;
 2import java.util.Arrays;
 3
 4public class Main {
 5    public static void main(String[] args) {
 6        Scanner scanner = new Scanner(System.in);
 7        int n = scanner.nextInt();
 8        scanner.nextLine();
 9
10        int[][] matrix = inputMatrix(n, scanner);
11        System.out.println(Arrays.deepToString(matrix));
12    }
13
14    public static int[][] inputMatrix(int n, Scanner scanner) {
15        int[][] matrix = new int[n][n];
16        String numsString;
17        String[] numsStringArray;
18        for (int i = 0; i < n; i++) {
19            numsString = scanner.nextLine();
20            numsStringArray = numsString.split("\\s+");
21            for (int j = 0; j < n; j++) {
22                if (j < numsStringArray.length) {
23                    matrix[i][j] = Integer.parseInt(numsStringArray[j]);
24                } else {
25                    matrix[i][j] = 0;
26                }
27            }
28        }
29        scanner.close();
30        return matrix;
31    }
32}
  1. 以上一题方法读入一个n * n的二维数组,输出该二维数组与其转置数组乘积后得到的新数组。
 1example:
 2
 3input:
 45
 53 2 1 7 6 8
 611 2 4 12 5
 74 3 1
 87 6 5
 91
10
11output:
12[[99, 155, 19, 38, 3], [155, 310, 54, 109, 11], [19, 54, 26, 51, 4], [38, 109, 51, 110, 7], [3, 11, 4, 7, 1]]
 1import java.util.Scanner;
 2import java.util.Arrays;
 3
 4public class Main {
 5    public static void main(String[] args) {
 6        Scanner scanner = new Scanner(System.in);
 7        int n = scanner.nextInt();
 8        scanner.nextLine();
 9
10        int[][] matrix = inputMatrix(n, scanner);
11        int[][] transposedMatrix = getTranspose(matrix, n);
12        int[][] resultMatrix = matrixMultiply(matrix, transposedMatrix, n);
13
14        System.out.println(Arrays.deepToString(resultMatrix));
15    }
16
17    public static int[][] inputMatrix(int n, Scanner scanner) {
18        int[][] matrix = new int[n][n];
19        String numsString;
20        String[] numsStringArray;
21
22        for (int i = 0; i < n; i++) {
23            numsString = scanner.nextLine();
24            numsStringArray = numsString.split("\\s+");
25            for (int j = 0; j < n; j++) {
26                matrix[i][j] = j < numsStringArray.length ? Integer.parseInt(numsStringArray[j]) : 0;
27            }
28        }
29
30        scanner.close();
31        return matrix;
32    }
33
34    public static int[][] getTranspose(int[][] matrix, int n) {
35        int T[][] = new int[n][n];
36        for (int i = 0; i < n; i++) {
37            for (int j = 0; j < n; j++) {
38                T[j][i] = matrix[i][j];
39            }
40        }
41        return T;
42    }
43
44    public static int[][] matrixMultiply(int[][] aMatrix, int[][] bMatrix, int n) {
45        int[][] resultMatrix = new int[n][n];
46        for (int i = 0; i < n; i++) {
47            for (int j = 0; j < n; j++) {
48                for (int k = 0; k < n; k++) {
49                    resultMatrix[i][j] += aMatrix[i][k] * bMatrix[k][j];
50                }
51            }
52        }
53        return resultMatrix;
54    }
55}
  1. 从键盘读入一个n,代表n位同学,依次读入n组由数字字符和空格组成的字符串,将其存储为一个 3 * n的二维数组。二维数组中每一项为一个浮点型数据,代表一位同学同一门课的三次考试的成绩(test1,test2,test3)。给定一个一维数组,代表每次考试的权值,该一维数组为[0.25, 0.25, 0.5],计算每个同学的最终得分,并输出统计这n个同学最终成绩的一维数组。(每个同学的成绩保留小数点后两位小数)。
 1example:
 2
 3input:
 44
 587 75 60
 666 98 100
 770 65 72
 867 77.5 80
 9
10output:
11[70.5, 91.0, 69.75, 76.12]
 1import java.util.Scanner;
 2import java.util.Arrays;
 3
 4public class Main {
 5    public static void main(String[] args) {
 6        Scanner scanner = new Scanner(System.in);
 7        int n = scanner.nextInt();
 8        scanner.nextLine();
 9
10        double[] result = new double[n];
11        String scoresString;
12        String[] scoresStringArray = new String[3];
13        double[] scores = new double[3];
14        double[] weights = { 0.25, 0.25, 0.5 };
15        double weightedSum;
16
17        for (int i = 0; i < n; i++) {
18            scoresString = scanner.nextLine();
19            scoresStringArray = scoresString.split("\\s+");
20            weightedSum = 0.0;
21            for (int j = 0; j < 3; j++) {
22                scores[j] = Double.parseDouble(scoresStringArray[j]);
23                weightedSum += scores[j] * weights[j];
24            }
25            result[i] = Math.round(weightedSum * 100) / 100.0; // 使用 Math.round() 四舍五入,随后除以 100.0 将 long 转换为 double
26        }
27
28        scanner.close();
29        System.out.println(Arrays.toString(result));
30    }
31}
  1. 计算小于n的最大素数。输入n的值小于等于2时,输出None
 1input:
 2100
 3
 4output:
 597
 6
 7input:
 8200
 9
10output:
11199
12
13input:
142
15
16output:
17None
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        try (Scanner scanner = new Scanner(System.in)) {
 6            int n = scanner.nextInt();
 7            if (n <= 2) {
 8                System.out.println("None");
 9            } else {
10                for (int i = n - 1; i >= 2; i--) {
11                    if (isPrime(i)) {
12                        System.out.println(i);
13                        break;
14                    }
15                }
16            }
17        }
18    }
19
20    public static boolean isPrime(int n) {
21        for (int i = 2; i * i <= n; i++) {
22            if (n % i == 0) {
23                return false;
24            }
25        }
26        return true;
27    }
28}
  1. 从键盘输入一个n,代表打印杨辉三角的行数,且n >=3 ,编写一个程序,打印杨辉三角。
 1input:
 23
 3
 4output:
 5[1]
 6[1, 1]
 7[1, 2, 1]
 8
 9input:
105
11
12output:
13[1]
14[1, 1]
15[1, 2, 1]
16[1, 3, 3, 1]
17[1, 4, 6, 4, 1]
 1import java.util.Scanner;
 2import java.util.ArrayList;
 3
 4public class Main {
 5    public static void main(String[] args) {
 6        int n;
 7        try (Scanner scanner = new Scanner(System.in)) {
 8            n = scanner.nextInt();
 9        }
10
11        ArrayList<Integer> current = new ArrayList<>();
12        current.add(1);
13        System.out.println(current);
14        if (n == 1) {
15            return;
16        }
17
18        for (int i = 2; i <= n; i++) {
19            ArrayList<Integer> previous = (ArrayList<Integer>) current.clone(); // 复制 current 得到 Object 对象,随后强制转换为
20                                                                                // ArrayList<Integer>
21            current = new ArrayList<>();
22            current.add(1);
23            for (int j = 1; j < i - 1; j++) {
24                current.add(previous.get(j - 1) + previous.get(j)); // ArrayList<Integer> 不能直接通过切片访问元素,需要使用
25                                                                    // ArrayList<Integer>.get() 方法
26            }
27            current.add(1);
28            System.out.println(current);
29        }
30    }
31}
  1. 编写一个函数能够判断两个字符串的最长前缀码,比如:distance和distinct的最长

前缀码为dist,如果输入的两个字符串没有相同的前缀码则返回None。

 1input:
 2distance
 3distinct
 4
 5output:
 6dist
 7
 8input:
 9student
10teacher
11
12output:
13None
14
15input:
16version
17versus
18
19output:
20vers
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        try (Scanner scanner = new Scanner(System.in)) {
 6            String aWord = scanner.nextLine();
 7            String bWord = scanner.nextLine();
 8            StringBuilder result = new StringBuilder();
 9            int minLength = Math.min(aWord.length(), bWord.length()); // String.length() 方法获得字符长度
10
11            for (int i = 0; i < minLength; i++) {
12                if (aWord.charAt(i) == bWord.charAt(i)) { // 通过 String.charAt() 方法访问字符
13                    result.append(aWord.charAt(i));
14                } else {
15                    System.out.println(i == 0 ? "None" : result.toString());
16                    return;
17                }
18            }
19            System.out.println(result.toString());
20        }
21    }
22}
  1. 因式分解,输入一个数,判断其实素数还是合数,如果是合数,将所有的因式分解打印出来
 1input:
 217
 3
 4output:
 517 is Prime
 6
 7input:
 820
 9
10output:
1120=1*20 20=2*10 20=4*5
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        int n;
 6        try (Scanner scanner = new Scanner(System.in)) {
 7            n = scanner.nextInt();
 8        }
 9
10        if (isPrime(n)) {
11            System.out.println(String.format("%d is prime", n));
12        }
13
14        for (int i = 1; i * i <= n; i++) {
15            if (n % i == 0) {
16                System.out.print(String.format("%d=%d*%d ", n, i, n / i));
17            }
18        }
19    }
20
21    public static boolean isPrime(int n) {
22        if (n <= 1) {
23            return false;
24        } else {
25            for (int i = 2; i * i <= n; i++) {
26                if (n % i == 0) {
27                    return false;
28                }
29            }
30            return true;
31        }
32    }
33}
  1. 编写函数,接收一个正偶数为参数,输出两个素数,并且这两个素数之和等于原来的正偶数。如果存在多组符合条件的素数,则全部输出。

如果输入的不是正偶数,打印输入错误。

 1input:
 220
 3
 4output:
 520=3+17
 620=7+13
 720=13+7
 820=17+3
 9
10input:
119
12
13output:
14input error!
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        int n;
 6        try (Scanner scanner = new Scanner(System.in)) {
 7            n = scanner.nextInt();
 8        }
 9
10        if (n % 2 != 0 || n <= 0) {
11            System.out.println("Input Error!");
12            return;
13        }
14
15        for (int i = 3; i < n - 2; i += 2) {
16            if (isPrime(i) && isPrime(n - i)) {
17                System.out.println(String.format("%d=%d+%d", n, i, n - i));
18            }
19        }
20    }
21
22    public static boolean isPrime(int n) {
23        if (n <= 1) {
24            return false;
25        } else {
26            for (int i = 2; i * i <= n; i++) {
27                if (n % i == 0) {
28                    return false;
29                }
30            }
31            return true;
32        }
33    }
34}
  1. 凯撒密码(Caesar Cypher)是一个比较弱的加密形式,它涉及将单词中的每个字母“轮转”固定数量的位置。轮转一个字母意思是在字母表中移动它,如果需要,再从开头开始。所以‘A’轮转3个位置是’D‘,而’Z‘轮转一个位置是’A‘。
1input:
2izieisie
35
4
5output:
6nenjnxnj
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        Scanner scanner = new Scanner(System.in);
 6        String plaintext = scanner.nextLine();
 7        int key = scanner.nextInt();
 8        scanner.close();
 9
10        String ciphertext = caeserEncrypt(plaintext, key);
11        System.out.println(ciphertext);
12    }
13
14    public static String caeserEncrypt(String plaintext, int key) {
15        StringBuilder ciphertext = new StringBuilder();
16        for (char c : plaintext.toCharArray()) { // 将 String 转化为 char 数组后才能遍历
17            char base = Character.isLowerCase(c) ? 'a' : 'A';
18            char encryptedChar = (char) ((c - base + key) % 26 + base);
19            ciphertext.append(encryptedChar);
20        }
21        return ciphertext.toString();
22    }
23}
  1. 从键盘输入一个十进制数n,再输入一个需要转换的进制数,输出十进制转换成对应进制的数。如果输入的转换进制不是2或8或16,输出错误提示。
 1example:
 2
 3input:
 432
 52
 6
 7output:
 8100000
 9
10input:
1132
128
13
14output:
1540
16
17input:
1832
1916
20
21output:
2220
23
24input:
2532
265
27
28output:
29Error!please input correct number(2 or 8 or 16)
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        try (Scanner scanner = new Scanner(System.in)) {
 6            int decimal = scanner.nextInt();
 7            int base = scanner.nextInt();
 8            String result = fromDecimal(base, decimal);
 9            System.out.println(result);
10        }
11    }
12
13    public static String fromDecimal(int base, int decimal) {
14        switch (base) {
15            case 2:
16                return Integer.toBinaryString(decimal);
17            case 8:
18                return Integer.toOctalString(decimal);
19            case 16:
20                return Integer.toHexString(decimal);
21            default:
22                return "Error! Please input a correct base (2, 8, 16).";
23        }
24    }
25}
  1. 从键盘接收一个由空格分隔的字符串如:AAF H D,将其存在数组中,第一个是需要转换进制的数值,第二个是当前的进制,第三个是需要转换的进制。输出转换的结果。(B代表二进制 , D代表十进制,O代表八进制,H代表十六进制)
 1example:
 2
 3input:
 423 D H
 5
 6output:
 717
 8
 9input:
101011 B O
11
12output:
1313
14
15input:
161011 H D
17
18output:
194113
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        Scanner scanner = new Scanner(System.in);
 6        String input = scanner.nextLine();
 7        scanner.close();
 8
 9        String[] inputArray = input.split("\\s+");
10        int decimal = convertToDecimal(inputArray[0], inputArray[1].charAt(0));
11        String result = convertToBase(decimal, inputArray[2].charAt(0));
12        System.out.println(result);
13    }
14
15    public static int convertToDecimal(String initialValueString, char initialBase) {
16        int decimal;
17        switch (initialBase) {
18            case 'B':
19                decimal = Integer.parseInt(initialValueString, 2);
20                break;
21            case 'O':
22                decimal = Integer.parseInt(initialValueString, 8);
23                break;
24            case 'D':
25                decimal = Integer.parseInt(initialValueString);
26                break;
27            case 'H':
28                decimal = Integer.parseInt(initialValueString, 16);
29                break;
30            default:
31                decimal = -1;
32                break;
33        }
34        return decimal;
35    }
36
37    public static String convertToBase(int decimal, char targetBase) {
38        String result;
39        switch (targetBase) {
40            case 'B':
41                result = Integer.toBinaryString(decimal);
42                break;
43            case 'O':
44                result = Integer.toOctalString(decimal);
45                break;
46            case 'D':
47                result = Integer.toString(decimal);
48                break;
49            case 'H':
50                result = Integer.toHexString(decimal);
51                break;
52            default:
53                result = "Invalid base";
54                break;
55        }
56        return result;
57    }
58}
  1. 《九章算术》是我国古代数学名著,卷七中有题:今有人合伙买羊,每人出5钱,会差45钱,每人出7钱会差3钱,问,合伙人数和钱数各是多少?
1input:
2None
3
4output:
5people:XX
6money:XX
 1import com.microsoft.z3.*; // 常规写法没意思,尝试使用 z3 库
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        Context context = null;
 6        try {
 7            context = new Context(); // 创建 z3 上下文
 8            IntExpr x = context.mkIntConst("x"); // 创建整型变量 x
 9            ArithExpr leftExpr = context.mkAdd(
10                    context.mkMul(context.mkInt(5), x),
11                    context.mkInt(45)); // 构建表达式 5x + 45
12            ArithExpr rightExpr = context.mkAdd(
13                    context.mkMul(context.mkInt(7), x),
14                    context.mkInt(3)); // 构建表达式 7x + 3
15            BoolExpr equation = context.mkEq(leftExpr, rightExpr); // 构建方程 5x + 45 = 7x + 3
16            Solver solver = context.mkSolver(); // 创建求解器
17            solver.add(new BoolExpr[] { equation }); // 添加方程到求解器
18
19            if (solver.check() == Status.SATISFIABLE) {
20                Model model = solver.getModel(); // 获取结果模型
21                int people = Integer.parseInt(model.getConstInterp(x).toString()); // 获取变量 x 的值
22                int money = 5 * people + 45; // 计算 money 的结果;
23
24                System.out.println("people: " + people);
25                System.out.println("money: " + money);
26            }
27        } catch (Z3Exception e) {
28            e.printStackTrace();
29        }
30    }
31}
  1. 问题描述

给定两个仅由大写字母或小写字母组成的字符串(长度介于1到10之间),它们之间的关系是以下4中情况之一: 1:两个字符串长度不等。比如 Beijing 和 Hebei 2:两个字符串不仅长度相等,而且相应位置上的字符完全一致(区分大小写),比如 Beijing 和 Beijing 3:两个字符串长度相等,相应位置上的字符仅在不区分大小写的前提下才能达到完全一致(也就是说,它并不满足情况2)。比如 beijing 和 BEIjing 4:两个字符串长度相等,但是即使是不区分大小写也不能使这两个字符串一致。比如 Beijing 和 Nanjing 编程判断输入的两个字符串之间的关系属于这四类中的哪一类,给出所属的类的编号。

输入格式

  包括两行,每行都是一个字符串

输出格式

  仅有一个数字,表明这两个字符串的关系编号

1样例输入
2
3BEIjing
4beiJing
5
6样例输出
7
83
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        String aString, bString;
 6        try (Scanner scanner = new Scanner(System.in)) {
 7            aString = scanner.nextLine();
 8            bString = scanner.nextLine();
 9        }
10
11        int result;
12        if (aString.length() > bString.length()) {
13            result = 1;
14        } else if (aString.equals(bString)) { // 比较两个字符串是否相等
15            result = 2;
16        } else if (aString.toLowerCase().equals(bString.toLowerCase())) {
17            result = 3;
18        } else {
19            result = 4;
20        }
21
22        System.out.println(result);
23    }
24}
  1. 连续字符,输入一个字符串,求出此字符串中最长连续字符的长度。
 1例:
 2
 3input:
 4abbcccddddeeeeedcba
 5
 6output:
 75
 8
 9input:
10hooraaaaaaaaaaay
11
12ouput:
1311
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        Scanner scanner = new Scanner(System.in);
 6        String input = scanner.nextLine();
 7        scanner.close();
 8
 9        int maxLength = 0;
10        int currentLength = 0;
11        char previousChar = '\0';
12        for (char currentChar : input.toCharArray()) {
13            if (currentChar == previousChar) {
14                currentLength++;
15            } else {
16                if (currentLength > maxLength) {
17                    maxLength = currentLength;
18                }
19                currentLength = 1;
20            }
21            previousChar = currentChar;
22        }
23        System.out.println(maxLength);
24    }
25}
  1. 给你一个整数 n(n>=2) ,请你判断 n 是否为 丑数 。如果是,返回 True ;否则,返回False 。

丑数 就是只包含质因数 2、3 和或 5 的正整数。

 1input:
 26
 3
 4output:
 5True
 6
 7input:
 814
 9
10output:
11False
 1import java.util.Scanner;
 2
 3public class Main {
 4    public static void main(String[] args) {
 5        Scanner scanner = new Scanner(System.in);
 6        int number = scanner.nextInt();
 7        scanner.close();
 8
 9        int factors[] = { 2, 3, 5 };
10        for (int i : factors) {
11            while (number % i == 0) {
12                number /= i;
13            }
14        }
15        System.out.println(number == 1);
16    }
17}
  1. 从键盘输入两个一维数组,再输入一个符号,符号可以是“+”“-”“*”“/”“//”,完成一维数组的加减乘除操作。如果两个一维数组的长度不同,将短的用0补齐,除法操作需要判断每一项除数是否为0,如果有除数为0的情况,返回“The divisor cannot be zero!”
 1example:
 2
 3input:
 4[2, 3, 5 ,7]
 5[1, 7, 6, 0 , 11, 20]
 6+
 7
 8ouput:
 9[3, 10, 11, 7, 11, 20]
10
11input:
12[2, 3, 5 ,7]
13[1, 7, 6, 0 , 11, 20]
14*
15
16output:
17[2, 21, 30, 0, 0, 0]
18
19input:
20[2, 3, 5 ,7]
21[1, 7, 6, 0 , 11, 20]
22//
23
24output:
25The divisor cannot be zero!
 1import java.util.Scanner;
 2import java.util.Arrays;
 3import java.util.stream.IntStream;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        String aNumArrayString;
 8        String bNumArrayString;
 9        String operator;
10        try (Scanner scanner = new Scanner(System.in)) {
11            aNumArrayString = scanner.nextLine();
12            bNumArrayString = scanner.nextLine();
13            operator = scanner.nextLine();
14        }
15
16        int[] aNumArray = parseIntArray(aNumArrayString);
17        int[] bNumArray = parseIntArray(bNumArrayString);
18
19        aNumArray = paddedArray(aNumArray, bNumArray.length);
20        bNumArray = paddedArray(bNumArray, aNumArray.length);
21
22        System.out.println(calculate(aNumArray, bNumArray, operator));
23    }
24
25    public static int[] parseIntArray(String numArrayString) {
26        String trimmedString = numArrayString.substring(1, numArrayString.length() - 1); // 去除中括号
27        String[] numStringArray = trimmedString.split("\\s*,\\s*");
28        int[] numArray = Arrays.stream(numStringArray).mapToInt(Integer::parseInt).toArray(); // 利用流将字符串数组转化为整型数组
29        return numArray;
30    }
31
32    public static int[] paddedArray(int[] array, int length) {
33        if (array.length >= length) {
34            return array;
35        }
36        int[] paddedArray = new int[length];
37        System.arraycopy(array, 0, paddedArray, 0, array.length); // System.arraycopy()方法用于数组复制
38        for (int i = array.length; i < length; i++) {
39            paddedArray[i] = 0;
40        }
41        return paddedArray;
42    }
43
44    public static String calculate(int[] aNumArray, int[] bNumArray, String operator) {
45        if (operator.equals("/") || operator.equals("//")) { // 使用 String.equals() 判断字符串是否相等
46            for (int i : bNumArray) {
47                if (i == 0) {
48                    return "Error: division by zero";
49                }
50            }
51        }
52        switch (operator) {
53            case "+":
54                return Arrays.toString(
55                        IntStream.range(0, aNumArray.length) // 使用 IntStream 计算数组元素之和
56                                .map(i -> aNumArray[i] + bNumArray[i])
57                                .toArray());
58            case "-":
59                return Arrays.toString(
60                        IntStream.range(0, aNumArray.length)
61                                .map(i -> aNumArray[i] - bNumArray[i])
62                                .toArray());
63            case "*":
64                return Arrays.toString(
65                        IntStream.range(0, aNumArray.length)
66                                .map(i -> aNumArray[i] * bNumArray[i])
67                                .toArray());
68            case "//":
69                return Arrays.toString(
70                        IntStream.range(0, aNumArray.length)
71                                .map(i -> aNumArray[i] / bNumArray[i])
72                                .toArray());
73            case "/":
74                return Arrays.toString(
75                        IntStream.range(0, aNumArray.length)
76                                .mapToDouble(i -> (double) aNumArray[i] / bNumArray[i])
77                                .toArray()); // DoubleStream.range() 方法不存在,使用 mapToDouble() 强制类型转换
78            default:
79                return "Error: invalid operator";
80        }
81    }
82}
  1. 从键盘输入一个一维数组,对一维数组中的元素进行全排列。一维数组中的元素数量不超过20位。(用递归完成)
 1example:
 2
 3input:
 4['a','b','c']
 5
 6output:
 7a b c
 8a c b
 9b a c
10b c a
11c b a
12c a b
 1package com.jackgdn; // 此题开始使用 Maven 构建
 2
 3import java.util.Scanner;
 4import com.google.gson.Gson; // 使用 gson 解析 json
 5import java.util.ArrayList;
 6import java.util.List;
 7
 8public class Main {
 9    public static void main(String[] args) {
10        String jsonString;
11        try (Scanner scanner = new Scanner(System.in)) {
12            jsonString = scanner.nextLine();
13        }
14
15        Gson gson = new Gson(); // 创建 Gson 对象
16        List<Character> chars = charArrayToList(gson.fromJson(jsonString, char[].class)); // 将 json 字符串转为 / List<Character>
17
18        List<List<Character>> permutations = permute(chars);
19        for (List<Character> charsList : permutations) {
20            for (Character c : charsList) {
21                System.out.print(String.format("%c ", c));
22            }
23            System.out.println();
24        }
25    }
26
27    public static List<Character> charArrayToList(char[] chars) {
28        List<Character> characterList = new ArrayList<>();
29        for (char c : chars) {
30            characterList.add(c);
31        }
32        return characterList;
33    }
34
35    public static List<List<Character>> permute(List<Character> chars) {
36        List<List<Character>> result = new ArrayList<>();
37        backtrack(chars, new ArrayList<>(), result);
38        return result;
39    }
40
41    public static void backtrack(List<Character> chars, List<Character> path, List<List<Character>> result) {
42        if (path.size() == chars.size()) {
43            result.add(new ArrayList<>(path));
44            return;
45        }
46
47        for (int i = 0; i < chars.size(); i++) {
48            if (path.contains(chars.get(i))) {
49                continue;
50            }
51            path.add(chars.get(i));
52            backtrack(chars, path, result);
53            path.remove(path.size() - 1);
54        }
55    }
56}
  1. Collatz猜想是一个未经证明的数学猜想,它说以下算法总是停止:

给定一个整数输入:

如果数字是1,停止。

如果数字是偶数,就除以2。使用这个新值作为输入并重新启动。

如果数字是奇数,就乘以3再加1。使用这个新值作为输入并重新启动。

从键盘输入一个n,使用递归完成这个collatz程序。

 1example:
 2
 3input:
 412
 5
 6output:
 712
 86
 93
1010
115
1216
138
144
152
161
17
18input:
1911
20
21output:
2211
2334
2417
2552
2626
2713
2840
2920
3010
315
3216
338
344
352
361
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4
 5public class Main {
 6    public static void main(String[] args) {
 7        Scanner scanner = new Scanner(System.in);
 8        int n = scanner.nextInt();
 9        scanner.close();
10        collatz(n);
11    }
12
13    public static void collatz(int n) {
14        System.out.println(n);
15        if (n == 1) {
16            return;
17        } else if (n % 2 == 0) {
18            collatz(n / 2);
19        } else {
20            collatz(3 * n + 1);
21        }
22    }
23}
  1. 已知有公式 $G=4\pi^2\frac{a^3}{p^2(m_1+m_2)}$ ,从键盘依次输入a,p,m1,m2的值,编辑公式,输出g的值。输出格式为“10.2f”
1example:
23
32.1
45
51.4
6
7output:
8     37.77
 1package com.jackgdn;
 2
 3import java.util.Scanner;
 4import java.util.Formatter;
 5
 6public class Main {
 7    public static void main(String[] args) {
 8        Double a, p, m1, m2;
 9        try (Scanner scanner = new Scanner(System.in)) {
10            a = scanner.nextDouble();
11            p = scanner.nextDouble();
12            m1 = scanner.nextDouble();
13            m2 = scanner.nextDouble();
14        }
15
16        Double g = 4 * Math.PI * Math.PI * a * a * a / (p * p * (m1 + m2));
17        Formatter formatter = new Formatter();
18        formatter.format("%10.2f", g); // 使用 Formatter() 格式化
19        System.out.println(formatter.toString());
20    }
21}

相关系列文章