Java基础练习题-数字各个位数相加

  • Integer types and operations: The sum of digits
  • 方法一:单纯使用基本算术运算符进行计算。
  • 方法二: 通过字符串形式
  • 方法三:利用%来循环处理
  • 方法四:转化为chat数组进行处理


Integer types and operations: The sum of digits

题目要求:给定一个三位数(100-999)。求其各个位数的和。(要求效率4星,满星四星)

方法一:单纯使用基本算术运算符进行计算。

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        System.out.println(num / 100 + num % 100 / 10 + num % 10);
    }
}

方法二: 通过字符串形式

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        char[] nums = String.valueOf(scanner.nextInt()).toCharArray();
        int total = 0;
        for (char num : nums) {
            total += Integer.parseInt(Character.toString(num));
        }
        System.out.println(total);
    }
}

方法三:利用%来循环处理

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // put your code here
        int number = scanner.nextInt();
        int result = 0;
        while (number > 0) {
            int digit = number % 10;
            number /= 10;
            result += digit;        
        }
        System.out.println(result);
    }
}

方法四:转化为chat数组进行处理

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        char[] nums = String.valueOf(scanner.nextInt()).toCharArray();
        int total = 0;
        for (char num : nums) {
            total += Integer.parseInt(Character.toString(num));
        }
        System.out.println(total);
    }
}