美文网首页
经典算法50例

经典算法50例

作者: 上杉丶零 | 来源:发表于2019-02-20 20:47 被阅读0次

    【题目1】有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,则每个月的兔子总数为多少。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            for (int i = 1; i <= 20; i++) {
                System.out.println(function(i));
            }
        }
    
        public static int function(int month) {
            if (month == 1 || month == 2) {
                return 1;
            } else {
                return function(month - 1) + function(month - 2);
            }
        }
    }
    

    【题目2】判断101-200之间有多少个素数,并输出所有素数。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            label: for (int i = 101; i <= 200; i++) {
                for (int j = 2; j <= Math.sqrt(i); j++) {
                    if (i % j == 0) {
                        continue label;
                    }
                }
    
                System.out.println(i);
            }
        }
    }
    

    【题目3】打印出所有的水仙花数。所谓水仙花数,是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个水仙花数,因为153 = 1 ^ 3 + 5 ^ 3 + 3 ^ 3

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            for (int i = 100; i <= 999; i++) {
                if (i == Math.pow(i / 100, 3) + Math.pow(i / 10 % 10, 3) + Math.pow(i % 10, 3)) {
                    System.out.println(i);
                }
            }
        }
    }
    

    【题目4】将一个正整数分解质因数。例如:输入90,打印出90 = 2 * 3 * 3 * 5

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int number = scanner.nextInt();
            StringBuilder stringBuilder = new StringBuilder(number + " = ");
    
            for (int i = 2; i <= Math.sqrt(number); i++) {
                if (number % i == 0) {
                    stringBuilder.append(i + " * ");
                    number /= i;
                    i--;
                }
            }
    
            stringBuilder.append(number);
            System.out.println(stringBuilder);
            scanner.close();
        }
    }
    

    【题目5】利用条件运算符的嵌套来完成此题:90分及以上的同学用A表示,60~89分之间的用B表示,60分以下的用C表示。

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int score = scanner.nextInt();
            System.out.println(score > 100 || score < 0 ? "Error" : score >= 90 ? "A" : score >= 60 ? "B" : "C");
            scanner.close();
        }
    }
    

    【题目6】输入两个正整数m和n,求其最大公约数和最小公倍数。

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int m = scanner.nextInt();
            int n = scanner.nextInt();
            int greatestCommonDivisor = function(m, n);
            int leastCommonMultiple = m * n / greatestCommonDivisor;
            System.out.println("最大公约数:" + greatestCommonDivisor + "\n最小公倍数:" + leastCommonMultiple);
            scanner.close();
        }
    
        public static int function(int m, int n) {
            while (true) {
                if ((m = m % n) == 0) {
                    return n;
                }
    
                if ((n = n % m) == 0) {
                    return m;
                }
            }
        }
    }
    

    【题目7】输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

    package leif;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            String s = scanner.nextLine();
            Map<String, Integer> sIMap = new HashMap<String, Integer>();
            sIMap.put("letter", 0);
            sIMap.put("whitespace", 0);
            sIMap.put("digit", 0);
            sIMap.put("other", 0);
    
            for (char c : s.toCharArray()) {
                if (Character.isLetter(c)) {
                    sIMap.put("letter", sIMap.get("letter") + 1);
                } else if (Character.isWhitespace(c)) {
                    sIMap.put("whitespace", sIMap.get("whitespace") + 1);
                } else if (Character.isDigit(c)) {
                    sIMap.put("digit", sIMap.get("digit") + 1);
                } else {
                    sIMap.put("other", sIMap.get("other") + 1);
                }
            }
    
            System.out.println(sIMap);
            scanner.close();
        }
    }
    

    【题目8】求s = a + aa + aaa + aaaa + aa...a的值,其中a是一个数字,几个数相加由键盘控制。

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            int a = scanner.nextInt();
            int temp = a;
            int sum = a;
    
            for (int i = 1; i < n; i++) {
                a = a * 10 + temp;
                sum += a;
            }
    
            System.out.println(sum);
            scanner.close();
        }
    }
    

    【题目9】一个数如果恰好等于它的因子之和,这个数就称为完数,例如6 = 1 + 2 + 3。编程找出1000以内的所有完数。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            for (int i = 1; i < 1000; i++) {
                int sum = 0;
    
                for (int j = 1; j <= i / 2; j++) {
                    if (i % j == 0) {
                        sum += j;
                    }
                }
    
                if (i == sum) {
                    System.out.println(i);
                }
            }
        }
    }
    

    【题目10】一球从100米高度自由落下,每次落地后反跳回原高度的一半再落下。求它在第10次落地时,共经过多少米,第10次反弹多高。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            double s = 0;
            double h = 100;
    
            for (int i = 1; i <= 10; i++) {
                s += h;
                h /= 2;
                s += h;
            }
    
            System.out.println("经过路程:" + (s - h));
            System.out.println("反弹高度:" + h);
        }
    }
    

    【题目11】有1、2、3、4四个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            int counter = 0;
    
            for (int a = 1; a <= 4; a++) {
                for (int b = 1; b <= 4; b++) {
                    for (int c = 1; c <= 4; c++) {
                        if (a != b && b != c && c != a) {
                            System.out.println("" + a + b + c);
                            counter++;
                        }
                    }
                }
            }
    
            System.out.println(counter);
        }
    }
    

    【题目12】企业发放的奖金根据利润提成,利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时,高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%;高于100万元时,超过100万元的部分按1%提成。从键盘输入当月利润I,求应发放奖金总数?

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            double I = scanner.nextDouble();
            double bonus = I > 10 ? I > 20 ? I > 40 ? I > 60 ? I > 100 ? function100_(I) : function60_100(I) : function40_60(I) : function20_40(I) : function10_20(I) : function_10(I);
            System.out.println(bonus);
            scanner.close();
        }
    
        public static double function_10(double I) {
            return I * 0.1;
        }
    
        public static double function10_20(double I) {
            return (I - 10) * 0.075 + function_10(10);
        }
    
        public static double function20_40(double I) {
            return (I - 20) * 0.05 + function10_20(20);
        }
    
        public static double function40_60(double I) {
            return (I - 40) * 0.03 + function20_40(40);
        }
    
        public static double function60_100(double I) {
            return (I - 60) * 0.015 + function40_60(60);
        }
    
        public static double function100_(double I) {
            return (I - 100) * 0.01 + function60_100(100);
        }
    }
    

    【题目13】一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            for (int i = -100; i <= 10000; i++) {
                if (Math.sqrt(i + 100) % 1 == 0) {
                    if (Math.sqrt(i + 100 + 168) % 1 == 0) {
                        System.out.println(i);
                    }
                }
            }
        }
    }
    

    【题目14】输入某年某月某日,判断这一天是这一年的第几天。

    package leif;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            String date = scanner.next();
            Calendar calendar = Calendar.getInstance();
    
            try {
                calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(date));
                System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
            } catch (ParseException e) {
                e.printStackTrace();
            } finally {
                scanner.close();
            }
        }
    }
    

    【题目15】输入三个整数x、y、z,请把这三个数由小到大输出。

    package leif;
    
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            int z = scanner.nextInt();
            int[] is = {x, y, z};
            Arrays.sort(is);
            System.out.println(Arrays.toString(is));
            scanner.close();
        }
    }
    

    【题目16】打印九九乘法表。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            for (int i = 1; i <= 9; i++) {
                for (int j = 1; j <= i; j++) {
                    System.out.print(j + " * " + i + " = " + (i * j) + "\t");
                }
    
                System.out.println();
            }
        }
    }
    

    【题目17】猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不过瘾,又多吃了一个。第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            int peach = 1;
    
            for (int i = 9; i >= 1; i--) {
                peach = (peach + 1) * 2;
            }
    
            System.out.println(peach);
        }
    }
    

    【题目18】两个乒乓球队进行比赛,各出三人,甲队为a、b、c三人,乙队为x、y、z三人,已抽签决定比赛名单。有人向队员打听比赛的名单,a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            char[] m = {'a', 'b', 'c'};
            char[] n = {'x', 'y', 'z'};
    
            for (int i = 0; i < m.length; i++) {
                for (int j = 0; j < n.length; j++) {
                    if ((m[i] == 'a' && n[j] == 'x') || (m[i] == 'a' && n[j] == 'y')) {
                        continue;
                    } else if ((m[i] == 'b' && n[j] == 'y') || (m[i] == 'b' && n[j] == 'z')) {
                        continue;
                    } else if ((m[i] == 'c' && n[j] == 'x') || (m[i] == 'c' && n[j] == 'z')) {
                        continue;
                    } else {
                        System.out.println(m[i] + " vs " + n[j]);
                    }
                }
            }
        }
    }
    

    【题目19】打印出如下图案(菱形)

       *
      ***
     *****
    *******
     *****
      ***
       *
    
    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int i = scanner.nextInt();
    
            for (int row = 1; row <= i; row++) {
                for (int col = 1; col <= Math.abs((i + 1) / 2 - row); col++) {
                    System.out.print(" ");
                }
    
                for (int col = 1; col <= i - 2 * Math.abs((i + 1) / 2 - row); col++) {
                    System.out.print("*");
                }
    
                System.out.println();
            }
    
            scanner.close();
        }
    }
    

    【题目20】有一分数序列:2/1、3/2、5/3、8/5、13/8、21/13……求出这个数列的前20项之和。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            double sum = 0;
    
            for (int i = 1; i <= 20; i++) {
                sum += getNumerator(i) / getDenominator(i);
            }
    
            System.out.println(sum);
        }
    
        public static double getNumerator(int numerator) {
            if (numerator == 1) {
                return 2;
            } else if (numerator == 2) {
                return 3;
            } else {
                return getNumerator(numerator - 1) + getNumerator(numerator - 2);
            }
        }
    
        public static double getDenominator(int denominator) {
            if (denominator == 1) {
                return 1;
            } else if (denominator == 2) {
                return 2;
            } else {
                return getNumerator(denominator - 1) + getNumerator(denominator - 2);
            }
        }
    }
    

    【题目21】求1! + 2! + 3! + … + 20!的和。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            int sum = 0;
    
            for (int i = 1; i <= 20; i++) {
                sum += getFactorial(i);
            }
    
            System.out.println(sum);
        }
    
        public static int getFactorial(int number) {
            if (number == 1) {
                return 1;
            } else {
                return number * getFactorial(number - 1);
            }
        }
    }
    

    【题目22】利用递归方法求5!。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            System.out.println(getFactorial(5));
        }
    
        public static int getFactorial(int number) {
            if (number == 1) {
                return 1;
            } else {
                return number * getFactorial(number - 1);
            }
        }
    }
    

    【题目23】有五个人坐在一起,问第5个人的岁数,他说比第4个人大两岁,问第4个人的岁数,他说比第3个人大两岁,问第三个人的岁数,他说比第2个人大两岁,问第2个人的岁数,他说比第1个人大两岁,最后问第1个人,他说是10岁。请问第五个人多大?

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            int age = 10;
    
            for (int i = 4; i >= 1; i--) {
                age +=2;
            }
    
            System.out.println(age);
        }
    }
    

    【题目24】输入一个不多于5位的正整数,求它是几位数并逆序打印出各位数字。

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int i = 10000;
    
            while ((i = scanner.nextInt()) >= 10000 || i <= 0) {
                System.out.println("输入一个不多于5位的正整数");
            }
    
            StringBuilder stringBuilder = new StringBuilder(i + "");
            System.out.println(stringBuilder.length());
            System.out.println(stringBuilder.reverse());
            scanner.close();
        }
    }
    

    【题目25】输入一个5位数,判断它是不是回文数。即个位与万位相同、十位与千位相同。

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int i = 0;
    
            while ((i = scanner.nextInt()) > 99999 || i < 10000) {
                System.out.println("输入一个5位数");
            }
    
            StringBuilder stringBuilder = new StringBuilder(i + "");
            System.out.println(stringBuilder.toString().equals(stringBuilder.reverse().toString()) ? "是回文数" : "不是回文数");
            scanner.close();
        }
    }
    

    【题目26】请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入第一个字母:");
            String letter1 = scanner.next();
    
            switch (letter1) {
                case "m":
                case "M":
                    System.out.println("星期一");
                    break;
                case "t":
                case "T":
                    System.out.print("请输入第二个字母:");
                    String letter2 = scanner.next();
    
                    switch (letter2) {
                        case "u":
                        case "U":
                            System.out.println("星期二");
                            break;
                        case "h":
                        case "H":
                            System.out.println("星期四");
                            break;
                        default:
                            System.out.println("Error");
                            break;
                    }
    
                    break;
                case "w":
                case "W":
                    System.out.println("星期三");
                    break;
                case "f":
                case "F":
                    System.out.println("星期五");
                    break;
                case "s":
                case "S":
                    System.out.print("请输入第二个字母:");
                    String letter3 = scanner.next();
    
                    switch (letter3) {
                        case "a":
                        case "A":
                            System.out.println("星期六");
                            break;
                        case "u":
                        case "U":
                            System.out.println("星期日");
                            break;
                        default:
                            System.out.println("Error");
                            break;
                    }
    
                    break;
                default:
                    System.out.println("Error");
                    break;
            }
    
            scanner.close();
        }
    }
    

    【题目27】求100之内的素数。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            label: for (int i = 2; i < 100; i++) {
                for (int j = 2; j <= Math.sqrt(i); j++) {
                    if (i % j == 0) {
                        continue label;
                    }
                }
    
                System.out.println(i);
            }
        }
    }
    

    【题目28】对10个数进行排序。

    package leif;
    
    import java.util.Arrays;
    
    public class Test {
        public static void main(String[] args) {
            int[] is = new int[10];
    
            for (int i = 0; i < is.length; i++) {
                is[i] = (int) (Math.random() * 100 + 1);
            }
    
            System.out.println(Arrays.toString(is));
            Arrays.sort(is);
            System.out.println(Arrays.toString(is));
        }
    }
    

    【题目29】求一个3*3矩阵对角线元素之和。

    package leif;
    
    import java.util.Arrays;
    
    public class Test {
        public static void main(String[] args) {
            int[][] iss = new int[3][3];
    
            for (int i = 0; i < iss.length; i++) {
                for (int j = 0; j < iss[i].length; j++) {
                    iss[i][j] = (int) (Math.random() * 100 + 1);
                }
            }
    
            System.out.println(Arrays.deepToString(iss));
            int sum = 0;
    
            for (int i = 0; i < iss.length; i++) {
                for (int j = 0; j < iss[i].length; j++) {
                    if (i == j) {
                        sum += iss[i][j];
                    }
                }
            }
    
            System.out.println(sum);
        }
    }
    

    【题目30】有一个已经排好序的数组,现输入一个数,要求按原来的规律将它插入数组中。

    package leif;
    
    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            Integer[] is = new Integer[10];
    
            for (int i = 0; i < is.length; i++) {
                is[i] = (int) (Math.random() * 100 + 1);
            }
    
            System.out.println(Arrays.toString(is));
            Arrays.sort(is);
            System.out.println(Arrays.toString(is));
            Integer[] newIs = new Integer[is.length + 1];
            System.arraycopy(is, 0, newIs, 0, is.length);
            newIs[newIs.length - 1] = scanner.nextInt();
            boolean isASC = false;
    
            for (int i = 0; i < is.length; i++) {
                if (is[i] == is[i + 1]) {
                    continue;
                }
    
                if (is[i] < is[i + 1]) {
                    isASC = true;
                }
    
                break;
            }
    
            if (isASC) {
                Arrays.sort(newIs);
            } else {
                Arrays.sort(newIs, new Comparator<Integer>() {
                    @Override
                    public int compare(Integer i1, Integer i2) {
                        return i2 - i1;
                    }
                });
            }
    
            System.out.println(Arrays.toString(newIs));
            scanner.close();
        }
    }
    

    【题目31】将一个数组逆序输出。

    package leif;
    
    import java.util.Arrays;
    
    public class Test {
        public static void main(String[] args) {
            int[] is = new int[10];
    
            for (int i = 0; i < is.length; i++) {
                is[i] = (int) (Math.random() * 100 + 1);
            }
    
            System.out.println(Arrays.toString(is));
    
            for (int i = is.length - 1; i >= 0; i--) {
                System.out.print(is[i] + " ");
            }
        }
    }
    

    【题目32】取一个整数a从右端开始的4~7位。

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int i = scanner.nextInt();
            String string = String .valueOf(i);
            System.out.println(string.substring(string.length() - 7, string.length() - 4 + 1));
            scanner.close();
        }
    }
    

    【题目33】打印出杨辉三角形。

    package leif;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int numRows = scanner.nextInt();
            List<List<Integer>> rowList = new ArrayList<List<Integer>>();
    
            for (int row = 0; row < numRows; row++) {
                List<Integer> colList = new ArrayList<Integer>();
    
                for (int col = 0; col <= row; col++) {
                    if (col == 0 || row == col) {
                        colList.add(1);
                    } else {
                        colList.add(rowList.get(row - 1).get(col) + rowList.get(row - 1).get(col - 1));
                    }
                }
    
                rowList.add(colList);
            }
    
            for (List<Integer> iList : rowList) {
                System.out.println(iList);
            }
    
            scanner.close();
        }
    }
    

    【题目34】输入3个数a、b、c,按大小顺序输出。

    package leif;
    
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int[] is = new int[3];
            is[0] = scanner.nextInt();
            is[1] = scanner.nextInt();
            is[2] = scanner.nextInt();
            Arrays.sort(is);
            System.out.println(Arrays.toString(is));
            scanner.close();
        }
    }
    

    【题目35】输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。

    package leif;
    
    import java.util.Arrays;
    
    public class Test {
        public static void main(String[] args) {
            int[] is = new int[10];
    
            for (int i = 0; i < is.length; i++) {
                is[i] = (int) (Math.random() * 100 + 1);
            }
    
            System.out.println(Arrays.toString(is));
    
            int maxIndex = 0;
            int minIndex = 0;
    
            for (int i = 0; i < is.length; i++) {
                if (is[i] > is[maxIndex]) {
                    maxIndex = i;
                }
    
                if (is[i] < is[minIndex]) {
                    minIndex = i;
                }
            }
    
            if (maxIndex != 0) {
                is[0] = is[0] ^ is[maxIndex];
                is[maxIndex] = is[0] ^ is[maxIndex];
                is[0] = is[0] ^ is[maxIndex];
            }
    
            if (minIndex != is.length - 1) {
                is[is.length - 1] = is[is.length - 1] ^ is[minIndex];
                is[minIndex] = is[is.length - 1] ^ is[minIndex];
                is[is.length - 1] = is[is.length - 1] ^ is[minIndex];
            }
    
            System.out.println(Arrays.toString(is));
        }
    }
    

    【题目36】有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数。例:1、2、3、4、5后移动2个位置变成:4、5、1、2、3。

    package leif;
    
    import java.util.LinkedList;
    import java.util.Queue;
    
    public class Test {
        public static void main(String[] args) {
            Queue<Integer> iQueue = new LinkedList<Integer>();
    
            int n = (int) (Math.random() * 10 + 1);
            System.out.println(n);
    
            for (int i = 0; i < n; i++) {
                iQueue.offer((int) (Math.random() * 100 + 1));
            }
    
            System.out.println(iQueue);
    
            int m = (int) (Math.random() * 10 + 1);
            System.out.println(m);
    
            for (int i = 0; i < m; i++) {
                iQueue.offer(iQueue.poll());
            }
    
            System.out.println(iQueue);
        }
    }
    

    【题目37】约瑟夫环:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。问最后留下的是原来的第几号。

    package leif;
    
    import java.util.LinkedList;
    import java.util.List;
    
    public class Test {
        public static void main(String[] args) {
            List<Integer> iList = new LinkedList<Integer>();
            int n = (int) (Math.random() * 10 + 1);
            System.out.println(n);
    
            for (int i = 1; i <= n; i++) {
                iList.add(i);
            }
    
            int k = (int) (Math.random() * 10 + 1);
            System.out.println(k);
            int m = (int) (Math.random() * 10 + 1);
            System.out.println(m);
    
            while (iList.size() > 1) {
                System.out.println(iList);
                k = (k + m - 1) % n;
    
                if (k == 0) {
                    k = iList.size();
                }
    
                iList.remove(k - 1);
                n -= 1;
            }
    
            System.out.println(iList);
        }
    }
    

    【题目38】编写一个方法求一个字符串的长度。

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.println(function(scanner.nextLine()));
            scanner.close();
        }
    
        public static int function(String s) {
            return s.length();
        }
    }
    

    【题目39】编写一个方法,当n为偶数时,调用方法求1/2 + 1/4 + … + 1/n,当n为奇数时,调用方法求1/1 + 1/3 + … + 1/n

    package leif;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.println(function(scanner.nextInt()));
            scanner.close();
        }
    
        public static double function(int n) {
            double sum = 0;
    
            if (n % 2 == 0) {
                for (int i = 2; i <= n; i += 2) {
                    sum += 1.0 / i;
                }
            } else {
                for (int i = 1; i <= n; i += 2) {
                    sum += 1.0 / i;
                }
            }
    
            return sum;
        }
    }
    

    【题目40】字符串排序。

    package leif;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.Random;
    
    public class Test {
        public static void main(String[] args) {
            Random random = new Random();
            List<String> sList = new ArrayList<String>();
    
            for (int i = 1; i <= 10; i++) {
                StringBuilder stringBuilder = new StringBuilder();
    
                for (int j = 1; j <= 10; j++) {
                    stringBuilder.append((char) random.nextInt(128));
                }
    
                sList.add(stringBuilder.toString());
            }
    
            System.out.println(sList);
            Collections.sort(sList);
            System.out.println(sList);
        }
    }
    

    【题目41】海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子凭据分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份;第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份。第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            int sum = 6;
    
            for (int i = 4; i >= 1; i--) {
                sum = sum * 5 + 1;
            }
    
            System.out.println(sum);
        }
    }
    

    【题目42】已知809 * ?? = 800 * ?? + 9 * ??,其中??代表的两位数,8 * ??的结果为两位数,9 * ??的结果为3位数。求??代表的两位数及809 * ??后的结果。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            for (int i = 12; i <= 12; i++) {
                if (809 * i == 800 * i + 9 * i) {
                    System.out.println(i + " " + (809 * i));
                }
            }
        }
    }
    

    【题目43】求0~7所能组成的奇数个数(数字不能重复)。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            int sum = 4 * 6;
    
            for (int i = 0; i < 6; i++) {
                sum *= 6 - i;
            }
    
            System.out.println(sum);
        }
    }
    

    【题目44】哥德巴赫猜想:证明一个大于2的偶数总能表示为两个素数之和。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            for (int n = 2; n <= 100; n += 2) {
                for (int i = 2; i <= n - 2; i++) {
                    if (function(i)) {
                        if (function(n - i)) {
                            System.out.println(n + " = " + i + " + " + (n - i));
                        }
                    }
                }
            }
        }
    
        public static boolean function(int n) {
            for (int i = 2; i <= Math.sqrt(n); i++) {
                if (n % i == 0) {
                    return false;
                }
            }
    
            return true;
        }
    }
    

    【题目45】判断一个素数能把几个9整除, 如999999 % 7 = 0

    package leif;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Test {
        public static void main(String[] args) {
            label: for (int i : function()) {
                StringBuilder stringBuilder = new StringBuilder("9");
    
                while (true) {
                    long l = 0L;
    
                    try {
                        l = Long.valueOf(stringBuilder.toString());
                    } catch (NumberFormatException e) {
                        System.out.println(i + " NumberFormatException");
                        continue label;
                    }
    
                    if (l % i == 0) {
                        System.out.println(stringBuilder + " % " + i + " = 0");
                        continue label;
                    }
    
                    stringBuilder.append(9);
                }
            }
        }
    
        public static List<Integer> function() {
            List<Integer> iList = new ArrayList<Integer>();
    
            label: for (int i = 2; i <= 100; i++) {
                for (int j = 2; j <= Math.sqrt(i); j++) {
                    if (i % j == 0) {
                        continue label;
                    }
                }
    
                iList.add(i);
            }
    
            System.out.println(iList);
            return iList;
        }
    }
    

    【题目46】两个字符串连接。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            String s1 = "1";
            long time = System.currentTimeMillis();
    
            for (int i = 0; i < 50000; i++) {
                s1 = s1 + "1";
            }
    
            System.out.println("加号所花费的时间:" + (System.currentTimeMillis() - time));
            String s2 = "2";
            time = System.currentTimeMillis();
    
            for (int i = 0; i < 50000; i++) {
                s2.concat("2");
            }
    
            System.out.println("cancat方法所花费的时间:" + (System.currentTimeMillis() - time));
            StringBuilder stringBuilder = new StringBuilder("3");
            time = System.currentTimeMillis();
    
            for (int i = 0; i < 50000; i++) {
                stringBuilder.append("3");
            }
    
            System.out.println("append方法所花费的时间:" + (System.currentTimeMillis() - time));
        }
    }
    

    【题目47】读取7个数(1~50)的整数值,每读取一个值,程序打印出该值个数的*

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            for (int i = 1; i <= 7; i++) {
                int random = (int) (Math.random() * 50 + 1);
                System.out.println(random);
    
                for (int r = 1; r <= random; r++) {
                    System.out.print("*");
                }
    
                System.out.println();
            }
        }
    }
    

    【题目48】某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5,然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换。

    package leif;
    
    public class Test {
        public static void main(String[] args) {
            int i = (int) (Math.random() * 9000 + 1000);
            System.out.println(i);
            int a = i / 1000;
            int b = i / 100 % 10;
            int c = i / 10 % 10;
            int d = i % 10;
            System.out.println("" + (d + 5) % 10 + (c + 5) % 10 + (b + 5) % 10 + (a + 5) % 10);
        }
    }
    

    【题目49】计算字符串中子串出现的次数。

    package leif;
    
    import java.util.Scanner;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入一个字符串:");
            String s1 = scanner.nextLine();
            System.out.println("请输入要查找的子字符串:");
            String s2 = scanner.nextLine();
            Pattern pattern = Pattern.compile(s2, Pattern.CANON_EQ);
            Matcher matcher = pattern.matcher(s1);
            int counter = 0;
    
            while (matcher.find()) {
                counter++;
            }
    
            System.out.println(s2 + "在" + s1 + "出现的次数为:" + counter);
            scanner.close();
        }
    }
    

    【题目50】有2个学生,每个学生有3门课的成绩,从磁盘文件中分别读入每个学生的学号、姓名和三门课成绩,计算出每个学生的总成绩,把原有的数据和计算出的数据输出到磁盘文件中。

    <?xml version="1.0" encoding="utf-8"?>
    <students>
      <student id="1">
        <name>小明</name>
        <subjects>
          <subject>
            <name>Java</name>
            <score>100</score>
          </subject>
          <subject>
            <name>Oracle</name>
            <score>80</score>
          </subject>
          <subject>
            <name>HTML</name>
            <score>90</score>
          </subject>
        </subjects>
        <totalScore>270</totalScore>
      </student>
      <student id="2">
        <name>小红</name>
        <subjects>
          <subject>
            <name>Java</name>
            <score>80</score>
          </subject>
          <subject>
            <name>Oracle</name>
            <score>70</score>
          </subject>
          <subject>
            <name>HTML</name>
            <score>100</score>
          </subject>
        </subjects>
        <totalScore>250</totalScore>
      </student>
    </students>
    
    package leif;
    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.dom4j.Attribute;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.SAXReader;
    import org.dom4j.io.XMLWriter;
    
    public class Test {
        public static void main(String[] args) {
            List<Student> studentList = new ArrayList<Student>();
            File file = new File("C:\\Users\\Administrator\\Desktop\\test50.xml");
            SAXReader saxReader = new SAXReader();
            saxReader.setEncoding("UTF-8");
    
            try {
                Document document = saxReader.read(file);
                parserXML(document, studentList);
                System.out.println(studentList);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
    
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            XMLWriter xmlWriter = null;
    
            try {
                FileWriter fileWriter = new FileWriter("C:\\Users\\Administrator\\Desktop\\newTest50.xml");
                xmlWriter = new XMLWriter(fileWriter, outputFormat);
                Document document = DocumentHelper.createDocument();
                createXML(document, studentList);
                xmlWriter.write(document);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (xmlWriter != null) {
                    try {
                        xmlWriter.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        public static void parserXML(Document document, List<Student> studentList) {
            Element studentsElement = document.getRootElement();
            List<Element> studentElementList = studentsElement.elements("student");
    
            if (studentElementList != null) {
                for (Element studentElement : studentElementList) {
                    Student student = new Student();
                    Attribute idAttribute = studentElement.attribute("id");
    
                    if (idAttribute != null) {
                        student.setId(Integer.valueOf(idAttribute.getText()));
                    }
    
                    Element nameElement = studentElement.element("name");
    
                    if (nameElement != null) {
                        student.setName(nameElement.getText());
                    }
    
                    double totalScore = 0;
                    Element subjectsElement = studentElement.element("subjects");
    
                    if (subjectsElement != null) {
                        List<Element> subjectElementList = subjectsElement.elements("subject");
    
                        if (subjectElementList != null) {
                            for (Element subjectElement : subjectElementList) {
                                Subject subject = new Subject();
                                Attribute nameAttribute = subjectElement.attribute("name");
    
                                if (nameAttribute != null) {
                                    subject.setName(nameAttribute.getText());
                                }
    
                                Element scoreElement = subjectElement.element("score");
    
                                if (scoreElement != null) {
                                    double score = Double.valueOf(scoreElement.getText());
                                    subject.setScore(score);
                                    totalScore += score;
                                }
    
                                student.addToSubjectList(subject);
                            }
                        }
                    }
    
                    student.setTotalScore(totalScore);
                    studentList.add(student);
                }
            }
        }
    
        public static void createXML(Document document, List<Student> studentList) {
            Element studentsElement = document.addElement("students");
    
            for (Student student : studentList) {
                Element studentElement = studentsElement.addElement("student");
                studentElement.addAttribute("id", String.valueOf(student.getId()));
                studentElement.addElement("name").setText(student.getName());
                Element subjectsElement = studentElement.addElement("subjects");
    
                for (Subject subject : student.getSubjectList()) {
                    Element subjectElement = subjectsElement.addElement("subject");
                    subjectElement.addAttribute("name", subject.getName());
                    subjectElement.addElement("score").setText(String.valueOf(subject.getScore()));
                }
    
                studentElement.addElement("totalScore").setText(String.valueOf(student.getTotalScore()));
            }
        }
    }
    
    class Student {
        private int id;
        private String name;
        private List<Subject> subjectList = new ArrayList<Subject>();
        private double totalScore;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public List<Subject> getSubjectList() {
            return subjectList;
        }
    
        public void addToSubjectList(Subject subject) {
            subjectList.add(subject);
        }
    
        public double getTotalScore() {
            return totalScore;
        }
    
        public void setTotalScore(double totalScore) {
            this.totalScore = totalScore;
        }
    
        @Override
        public String toString() {
            return "Student [id=" + id + ", name=" + name + ", subjectList=" + subjectList + ", totalScore=" + totalScore + "]";
        }
    }
    
    class Subject {
        private String name;
        private double score;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public double getScore() {
            return score;
        }
    
        public void setScore(double score) {
            this.score = score;
        }
    
        @Override
        public String toString() {
            return "Subject [name=" + name + ", score=" + score + "]";
        }
    }
    

    相关文章

      网友评论

          本文标题:经典算法50例

          本文链接:https://www.haomeiwen.com/subject/jxnbhqtx.html