如何在java中对整数的数字求和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27096670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:48:22  来源:igfitidea点击:

How to sum digits of an integer in java?

javaparsing

提问by Shane Larsen

I am having a hard time figuring out the solution to this problem. I am trying to develop a program in Java that takes a number, such as 321, and finds the sum of digits, in this case 3 + 2 + 1 = 6. I need all the digits of any three digit number to add them together, and store that value using the % remainder symbol. This has been confusing me and I would appreciate anyones ideas.

我很难找出这个问题的解决方案。我正在尝试用 Java 开发一个程序,它需要一个数字,例如 321,并找到数字的总和,在本例中为 3 + 2 + 1 = 6。我需要任何三位数的所有数字将它们加在一起,并使用 % 余数符号存储该值。这让我很困惑,我会很感激任何人的想法。

采纳答案by Ankur Singhal

public static void main(String[] args) {
        int num = 321;
        int sum = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        System.out.println(sum); 
}

Output

输出

6

回答by Simon Woo

The following method will do the task:

以下方法将完成任务:

public static int sumOfDigits(int n) {
    String digits = new Integer(n).toString();
    int sum = 0;
    for (char c: digits.toCharArray())
        sum += c - '0';
    return sum;
}

You can use it like this:

你可以这样使用它:

System.out.printf("Sum of digits = %d%n", sumOfDigits(321));

回答by Arunkumar Papena

Here is a simple program for sum of digits of the number 321.

这是一个简单的程序,用于计算数字 321 的数字总和。

  import java.math.*;

        class SumOfDigits {
            public static void main(String args[]) throws Exception {
                int sum = 0;
                int i = 321;
                    sum = (i % 10) + (i / 10);
                        if (sum > 9) {
                            int n = (sum % 10) + (sum / 10);
                            System.out.print("Sum of digits of " + i + " is " + n);

                        }else{
                           System.out.print("Sum of digits of " + i + " is " + sum );     

    }

                }
        }


Output:

Sum of digits of 321 is 6

Or simple you can use this..check below program.

或者简单的你可以使用这个..检查下面的程序。

public class SumOfDigits {

public static void main(String[] args) 
{
    long num = 321;

/*  int rem,sum=0;
    while(num!=0)
    {
        rem = num%10;
        sum = sum+rem;
        num=num/10;
    }
    System.out.println(sum);

    */
    if(num!=0)
    {
        long sum = ((num%9==0) ? 9 : num%9);
        System.out.println(sum);
    }

}

回答by Ramesh Babu

Click here to see full program

单击此处查看完整程序

Sample code:

示例代码:

public static void main(String args[]) {
    int number = 333;
    int sum = 0;
    int num = number;
    while (num > 0) {
        int lastDigit = num % 10;
        sum += lastDigit;
        num /= 10;
    }
    System.out.println("Sum of digits : "+sum);
}

回答by krmanish007

In Java 8, this is possible in a single line of code as follows:

在 Java 8 中,这可以在一行代码中实现,如下所示:

int sum = Pattern.compile("")
        .splitAsStream(factorialNumber.toString())
        .mapToInt(Integer::valueOf)
        .sum();

回答by CyprUS

It might be too late, but I see that many solutions posted here use O(n^2) time complexity, this is okay for small inputs, but as you go ahead with large inputs, you might want to reduce time complexity. Here is something which I worked on to do the same in linear time complexity.

可能为时已晚,但我看到这里发布的许多解决方案使用 O(n^2) 时间复杂度,这对于小输入是可以的,但是当您继续处理大输入时,您可能希望降低时间复杂度。这是我在线性时间复杂度上做同样的事情。

NOTE : The second solution posted by Arunkumar is constant time complexity.

注意:Arunkumar 发布的第二个解决方案是恒定时间复杂度。

    private int getDigits(int num) {
    int sum =0;
    while(num > 0) { //num consists of 2 digits max, hence O(1) operation
        sum = sum + num % 10;
        num = num / 10;
    }   
    return sum;
}
public int addDigits(int N) {
    int temp1=0, temp2= 0;
    while(N > 0) {
        temp1= N % 10;
        temp2= temp1 + temp2;
        temp2= getDigits(temp2); // this is O(1) operation
        N = N/ 10;
    }
    return temp2;
}   

Please ignore my variable naming convention, I know it is not ideal. Let me explain the code with sample input , e.g. "12345". Output must be 6, in a single traversal.

请忽略我的变量命名约定,我知道这并不理想。让我用示例输入解释代码,例如“12345”。在单次遍历中输出必须为 6。

Basically what I am doing is that I go from LSB to MSB , and add digits of the sum found, in every iteration.

基本上我所做的是从 LSB 到 MSB ,并在每次迭代中添加找到的总和的数字。

The values look like this

这些值看起来像这样

Initially temp1 = temp2 = 0

最初 temp1 = temp2 = 0

N     | temp1 ( N % 10)  | temp2 ( temp1 + temp2 )
12345 | 5                | 5   
1234  | 4                | 5 + 4 = 9 ( getDigits(9) = 9)
123   | 3                | 9 + 3 = 12 = 3 (getDigits(12) =3 )
12    | 2                | 3 + 2 = 5 (getDigits(5) = 5)
1     | 1                | 5 + 1 = 6 (getDigits(6) = 6 )

Answer is 6, and we avoided one extra loop. I hope it helps.

答案是 6,我们避免了一个额外的循环。我希望它有帮助。

回答by user1139428

May be little late ..but here is how you can do it recursively

可能有点晚了..但这里是你如何递归地做到这一点

public int sumAllDigits(int number) {
    int sum = number % 10;

    if(number/10 < 10){
        return sum + number/10;
    }else{
        return sum + sumAllDigits(number/10);
}

回答by SlwoJams

Mine is more simple than the others hopefully you can understand this if you are a some what new programmer like myself.

我的比其他的更简单,希望你能理解这一点,如果你是一个像我这样的新程序员。

import java.util.Scanner;
import java.lang.Math;

public class DigitsSum {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int digit = 0;
        System.out.print("Please enter a positive integer: ");
        digit = in.nextInt();
        int D1 = 0;
        int D2 = 0;
        int D3 = 0;
        int G2 = 0;
        D1 = digit / 100;
        D2 = digit % 100;
        G2 = D2 / 10;
        D3 = digit % 10;


        System.out.println(D3 + G2 + D1);

    }
}

回答by Ridham Tarpara

This should be working fine for any number of digits and it will return individual digit's sum

这应该适用于任意数量的数字,它会返回单个数字的总和

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("enter a string");
    String numbers = input.nextLine();  //String would be 55
    int sum = 0;
    for (char c : numbers.toCharArray()) {
        sum += c - '0';
    }
    System.out.println(sum); //the answer is 10
}

回答by Chris Johnson

shouldn't you be able to do it recursively something like so? I'm kinda new to programming but I traced this out and I think it works.

你不应该像这样递归地做吗?我对编程有点陌生,但我追踪到了这一点,我认为它有效。

int sum(int n){
return n%10 + sum(n/10);
}