Java经典基础编程练习100题

Java萌新,在网上随机搜索Java基础编程练习题, 在此写一下解题思路。

1. 请实现一个算法,确定一个字符串的所有字符是否全都不同。这里我们要求不允许使用额外的存储结构。

解题思路: 双重for循环进行判断

   public static boolean ifAllCharsUnique(String s) {
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            for (int j = i + 1 ; j < chars.length; j++) {
                if (chars[i] == chars[j]) {
                    return false;
                }
            }
        }
        return true;
    }

不限制数据结构的话, 可以用set

	public static boolean ifAllCharsUnique(String s) {
        char[] chars = s.toCharArray();
        HashSet<Character> set = new HashSet<>();
        for (int i = 0; i < chars.length; i++) {
            set.add(chars[i]);
        }
        if (set.size() != chars.length) {
            return false;
        }
        return true;
    }
3. 打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

解题思路: 分别get三位数的百位, 十位和个位, 然后求三次方和, 与原数比较

	public static void armstrongNumber() {
        for (int i = 100; i < 1000; i++) {
            double first =  i / 100;
            double second = i % 100 / 10;
            double third = i % 10;
            double total = Math.pow(first, 3) + Math.pow(second, 3) + Math.pow(third, 3);
            if (total == i) {
                System.out.println(i);
            }
        }
    }
4. 将一个正整数分解质因数。例如:输入90,打印出90=233*5。

解题思路:
1、 将正整数从2开始整除, 如果可以整除,则将整除后的结果继续除
2、如果不能整除, 则将分母+1
3、直到整除后的结果==分母

	public static void getFactors(int n) {
        if (n < 1) {
            return;
        }
        if (n == 1 || n == 2) {
            System.out.println(n);
        }
        int k = 2;
        while (n != 1) {
            if (n == k) {
                System.out.println(k);
                break;
            }
            if (n % k == 0){
                System.out.print(k + "*");
                n = n / k;
            } else {
                k ++;
            }
        }
    }
5. 利用条件运算符的嵌套来完成此题:学习成绩> =90 分的同学用 A 表示,60-89 分之间的用 B 表示,60 分以下的用 C 表示。

解题思路:
条件运算符
condition1?result1
:condition2*?result2
:defaultResult

    public static void printScoreLevel(int score){
        if (score > 100 || score < 0) {
            return;
        }

        String level = score >= 90 ? "A"
                : score >= 60 && score < 90 ? "B"
                : "C";
        System.out.println(level);
    }
6. 求两数的最大公约数和最小公倍数

解题思路:

  • 最大公约数:在循环中,只要除数不等于 0,用较大数除以较小的数,将小的一个数作为下一轮循环的大数,取得的余数作为下一轮循环的较小的数,如此循环直到较小的数的值为 0,返回较大的数,此数即为最大公约数,
  • 最小公倍数:为两数之积除以最大公约数。
    /*
    求最大公约数
     */
    public static int greatestCommonDivisor(int a, int b) {
        if(a < b) {
            int temp = a;
            a = b;
            b = temp;
        }
        while(b != 0) {
            if (a == b) {
                return a;
            }
            int k = a % b;
            a = b;
            b = k;
        }
        return a;
    }
    
    /*
    求最小公倍数
     */
    public static int leastCommonMultiple(int a, int b){
        return a * b / greatestCommonDivisor(a, b);
    }
7. 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数

解题思路: 使用toCharArray()将字符串转换成字符数组, 然后使用Character类的静态方法判断字符类型

    public static void statisticCharAmount(){
        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();
        scanner.close();

        int letterAmount = 0, digitAmount = 0, spaceAmount = 0, otherAmount = 0;
        char[] chars = line.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (Character.isLetter(chars[i])) {
                letterAmount ++;
            } else if (Character.isDigit(chars[i])) {
                digitAmount ++;
            } else if (Character.isSpaceChar(chars[i])) {
                spaceAmount ++;
            } else {
                otherAmount ++;
            }
        }
        System.out.println("字母数量:" + letterAmount);
        System.out.println("数字数量:" + digitAmount);
        System.out.println("空格数量:" + spaceAmount);
        System.out.println("其他字符数量:" + otherAmount);
    }
8.求s=a+aa+aaa+aaaa+aa…a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。

解题思路:用StringBuilder生成对应的数字

    public static int numAdd() {
        int sum = 0;
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.print("Input a:");
            int a = scanner.nextInt();
            System.out.print("Input n:");
            int n = scanner.nextInt();

            for (int i = 1; i <= n; i++) {
                StringBuilder builder = new StringBuilder();
                for (int j = 0; j < i; j++) {
                    builder.append(a);
                }
                System.out.println(builder);
                sum += Integer.valueOf(builder.toString());
            }
        } finally {
            scanner.close();
        } 
        return sum;
    }
9. 一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。

解题思路:

    public static boolean ifPerfectNum(int n){
        int sum = 0;
        for (int i = 1; i <= n>>1 ; i++) {
            if (n % i == 0) {
                sum += i;
            }
        }
        return sum == n;
    }
    
    public static List<Integer> getPerfectNums(int range) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 1; i <= range; i++) {
            if (ifPerfectNum(i)) {
                list.add(i);
            }
        }
        return list;
    }
10.一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在 第10次落地时,共经过多少米?第10次反弹多高?

解题思路:

    public static void ballHeight() {
        double height = 100;
        int sum = 100;
        int n = 1;

        while (n < 11){
            height = height / 2;
            System.out.println("第"+ n + "次弹起, 高度"+ height + "米");
            n ++;
            sum += height * 2;
            System.out.println("第"+ n + "次落地, 高度"+ sum + "米");
        }
    }
11. 有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。

解题思路: 暴力穷举, 三个for循环嵌套, 分别取百位, 十位和个位

 public static void noDuplicatedNum() {
        int[] array = {1, 2, 3, 4};
        int count = 0;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                for (int k = 0; k < 4; k++) {
                    if ((i != j) && ( i != k) && (j != k)) {
                        System.out.println(array[i] * 100  + array[j] * 10 + array[k]);
                        count ++;
                    }
                }
            }
        }
        System.out.println(count);
    }
12. 写一个方法来判断一个String是否是回文

解题思路:
回文就是一个字符串, 正序和倒叙都是一样的, 比如 “ohhAhho”
将String转换为char[], 如果char[]的从首尾遍历元素都相等, 是一个对称结构, 就返回true, 任意一个元素不相等,就返回false。

    public static boolean ifSymmetric(String s) {
        char[] chars = s.toCharArray();
        for(int i=0; i<chars.length >> 1; i ++) {
            if (chars[i] != chars[chars.length-1-i]) {
                return false;
            }
        }
        return true;
    }
13. 给定一个字符串,判断该字符串中是否包含某个子串.如果包含,求出子串的所有出现位置.如:"abcbcbabcb34bcbd"中,"bcb"子串的出现位置为: 1,7,12.字符串和子串均由用户输入

解题思路:根据子串的长度,遍历字符串所有的子串, 如果string.substring(i, i + subString.length()) 与subString相等, 则打印字符串的下标

    public static void printSubstringPositions(String s, String subS) {
        for (int i = 0; i <= s.length() - subS.length(); i++) {
            if (s.substring(i, i + subS.length()).equals(subS)) {
                System.out.println(i);
            }
        }
    }
14. 输入某年某月某日,判断这一天是这一年的第几天?

解题思路: 考虑闰年的情况

    public static int certainDayInAYear(int year, int month ,int day) {
        HashMap<Integer, Integer> months = new HashMap<Integer, Integer>() {{
            put(1, 31);
            put(2, 28);
            put(3, 31);
            put(4, 30);
            put(5, 31);
            put(6, 30);
            put(7, 31);
            put(8, 31);
            put(9, 30);
            put(10, 31);
            put(11, 30);
            put(12, 31);
        }};

        if((year%400)==0 || ((year%4)==0)&&((year%100)!=0)) {
            months.put(2, 29);
        }

        int days = 0;
        for (int i = 1; i < month; i++) {
            days += months.get(i);
        }
        days += day;
        return days;
    }
15.题目:输入三个整数x,y,z,请把这三个数由小到大输出。

解题思路: 使用最简单的冒泡排序

    public static void sortAndPrint(int a, int b, int c){
        int[] array = {a, b, c};

        for (int i = array.length - 1; i >= 0 ; i--) {
            for (int j = 0; j < i; j++) {
                if (array[j] > array[i]) {
                    int temp = array[j];
                    array[j] = array[i];
                    array[i] = temp;
                }
            }
        }
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[array.length - 1 - i]);
        }
    }
16. 输出9*9口诀。

解题思路: 两层for循环嵌套

    public static void printLittleNineNine() {
        for (int i = 1; i < 10; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + "*" + i + "=" + i * j + " ");
            }
            System.out.println();
        }
    }
17.兔子个数

有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

解题思路:
第一个月: 1对兔子
第二个月: 1对兔子
第三个月: 第一个月的兔子生了, 2对兔子
第四个月: 第一个月的兔子又生了,3对兔子
第五个月: 第一个月的兔子叕生了, 第三个月的兔子生了, 4对 + 第四个月刚出生的兔子, 5对兔子
解题规律是: 第N个月的兔子数量=第N-2个月兔子数量*2 + 第N-1个月刚出生的兔子, 其中第N-1个月刚出生的萌新兔子=第N-1个月总的兔子数量-第N-2个月总的兔子数量

代码:

public static int getRabbitAmount(int month) {
        if (month <= 2) {
            return 1;
        }

        while (month > 2) {
            return getRabbitAmount(month - 2) * 2 +
                    getRabbitAmount(month - 1) - getRabbitAmount(month - 2);
        }
        return 0;
    }
18. 判断 101-200 之间有多少个素数,并输出所有素数。

解题思路: 遍历 [2, Math.sqrt(n)]之间所有的整数, 如果能被任意数整除, 就不是素数

	public static List<Integer> getPrimeNums() {
        ArrayList<Integer> nums = new ArrayList<>();
        for (int num = 101; num < 201; num++) {
            boolean flag = true;
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    flag = false;
                    break;
                }
            }
            if(flag) {
                nums.add(num);
            }
        }
        return nums;
    }
19.打印出如下图案(菱形)
   *   
  ***  
 ***** 
*******
 ***** 
  ***  
   *   
    public static void printDiamond(int n) {
        int mid = n >> 1;
        int range = 0;
        for (int i = 0; i < n; i++) {
            if (i <= mid) {
                range = i;
            } else {
                range = n - 1 - i;
            }
            for (int j = 0; j < n; j++) {
                if (j >= mid - range && j <= mid + range) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
* 20. 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13…求出这个数列的前 20 项之和
    public static double getSum(int n){
        int x = 2, y = 1;
        double sum = 0;
        for (int i = 0; i < n; i++) {
            sum = sum + x / y;
            x = x ^ y;
            y = x ^ y;
            x = x ^ y;
            x = x + y;
            System.out.println(x + "/" + y);
        }
        return sum;
    }

21.求 1+2!+3!+…+n!的和
public static int getSum2(int n) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            int x = 1;
            for (int j = 1; j <= i; j++) {
                x = x * j;
            }
            sum += x;
        }
        System.out.println(sum);
        return sum;
    }
22. 利用递归求n!
public static int getResult(int n) {
        if (n == 0) {
            return 0;
        }else if (n == 1) {
            return 1;
        } else {
            return getResult(n-1) * n;
        }
    }
  • 6
    点赞
  • 82
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值