[java] How to sum digits of an integer in java?

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.

This question is related to java parsing

The answer is


In addition to the answers here, I can explain a little bit. It is actually a mathematical problem.

321 is the total of 300 + 20 + 1.

If you divide 300 by 100, you get 3.

If you divide 20 by 10, you get 2.

If you divide 1 by 1, you get 1.

At the end of these operations, you can sum up all of them and you get 6.

public class SumOfDigits{

public static void main(String[] args) {
    int myVariable = 542;
    int checker = 1;
    int result = 0;
    int updater = 0;

    //This while finds the size of the myVariable
    while (myVariable % checker != myVariable) {
        checker = checker * 10;
    }

    //This for statement calculates, what you want.
    for (int i = checker / 10; i > 0; i = i / 10) {

        updater = myVariable / i;
        result += updater;
        myVariable = myVariable - (updater * i);
    }

    System.out.println("The result is " + result);
}
}

Here is a simple program for sum of digits of the number 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);
    }

}

without mapping ? the quicker lambda solution

Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c - '0' ) );

…or same with the slower % operator

Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c % '0' ) );


…or Unicode compliant

Integer.toString( num ).codePoints().boxed().collect( Collectors.summingInt( Character::getNumericValue ) );

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);

    }
}

If you need a one-liner I guess this is a very nice solution:

int sum(int n){
  return n >= 10 ? n % 10 + sum(n / 10) : n;
}

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);
}

Recursions are always faster than loops!

Shortest and best:

public static long sumDigits(long i) {
    return i == 0 ? 0 : i % 10 + sumDigits(i / 10);
}

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);
}

You can do it using Recursion

//Sum of digits till single digit is obtained
public int sumOfDigits(int num) 
        {
            int sum = 0;

            while (num > 0)
            {
                sum = sum + num % 10;
                num = num / 10;
            }

            sum = (sum <10) ? sum : sumOfDigits(sum);

            return sum;
        }

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
}

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);
}

In Java 8,

public int sum(int number) {
  return (number + "").chars()
                      .map(digit -> digit % 48)
                      .sum();
}

Converts the number to a string and then each character is mapped to it's digit value by subtracting ascii value of '0' (48) and added to the final sum.


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

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

If you love constant time try this:

double d = 10984.491;

// converting to String because of floating point issue of precision
String s = new String(d + "").replaceAll("\\D+","");
int i = Integer.parseInt(s);      

System.out.println(i % 9 == 0 ? 9 : i % 9);

Logic is if you add any number by 9, resulting addition of digit will result in the same number.

Example: 6 + 9 = 15 then 1 + 5 = 6 (again you got 6).

In case of decimal point, remove it and add resulting digits.

Below code does the trick:

i % 9 == 0 ? 9 : i % 9

Sums all the digits regardless of number's size.

private static int sumOfAll(int num) {
    int sum = 0;

    if(num == 10) return 1;

    if(num > 10) {
        sum += num % 10;
        while((num = num / 10) >= 1) {
            sum += (num > 10) ? num%10 : num;
        }
    } else {
        sum += num;
    }
    return sum;
}

Java 8 Recursive Solution, If you dont want to use any streams.

UnaryOperator<Long> sumDigit = num -> num <= 0 ? 0 : num % 10 + this.sumDigit.apply(num/10);

How to use

Long sum = sumDigit.apply(123L);

Above solution will work for all positive number. If you want the sum of digits irrespective of positive or negative also then use the below solution.

UnaryOperator<Long> sumDigit = num -> num <= 0 ? 
         (num == 0 ? 0 : this.sumDigit.apply(-1 * num)) 
         : num % 10 + this.sumDigit.apply(num/10);

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));

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.

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

    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.

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

The values look like this

Initially 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.


A simple solution using streams:

int n = 321;
int sum = String.valueOf(n)
    .chars()
    .map(Character::getNumericValue)
    .sum();

Java 8 Solution:

int n= 29;    
String.valueOf(n).chars().map(Character::getNumericValue).sum()