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.
-
Are you trying to calculate the digital root of any three digit number? If so, which part is causing you trouble? – Matt Coubrough Nov 24 '14 at 01:40
-
Well im just trying to take any number such as 480 and have it equal all of its digits (4, 8, 1) to add together using the % symbol. I need to create a loop in Java that can do this. – Shane Larsen Nov 24 '14 at 01:41
-
need to finish this code: Public static void main(String[] args) { int digits = 321; int sum..... System.out.printIn(sum); } – Shane Larsen Nov 24 '14 at 01:42
-
@ShaneLarsen have a look at the answer – Ankur Singhal Nov 24 '14 at 01:43
-
It seems like you already have the number as an int - I had assumed your input was a string - (otherwise I don't really understand which part of this essentially mathematical problem is causing you trouble) – Matt Coubrough Nov 24 '14 at 01:50
-
No [tag:parsing] required here, just arithmetic. – user207421 Feb 24 '22 at 03:56
22 Answers
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

- 76,500
- 11
- 62
- 80

- 26,012
- 16
- 82
- 116
-
-
This works. @ShaneLarsen class, interface or enum expected usually means your missing a curly bracket. – Michael Queue Nov 24 '14 at 02:02
-
9It's obiouds OP is asking to do his homework, and hasn't even put the main function into a class. – Martin Konecny Nov 24 '14 at 02:08
-
A simple solution using streams:
int n = 321;
int sum = String.valueOf(n)
.chars()
.map(Character::getNumericValue)
.sum();

- 49,289
- 6
- 73
- 138
Recursions are always faster than loops!
Shortest and best:
public static long sumDigits(long i) {
return i == 0 ? 0 : i % 10 + sumDigits(i / 10);
}

- 75
- 1
- 3
-
13
-
-
1
-
Recursion is not necessarily faster. In fact, it is very expensive in terms of space complexity, so if you have a loop solution, I recommend using that over recursion. – kc_dev Jul 10 '22 at 02:58
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;
}

- 335
- 3
- 13
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

- 15,456
- 11
- 71
- 120
-
It's not the answer to the question, cause this solution sums recursively, for ex: `456 -> 4+5+6 = 15 -> 1+5 = 6`, indead of `456 -> 4+5+6 = 15` But it fits my case, so +1 :) – fightlight Jul 11 '18 at 09:15
-
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 ) );

- 2,572
- 13
- 14
-
Is this actually quicker? Or just the quicker version in lambda form? – Beauregard Lionett Apr 27 '20 at 19:07
-
Yes, I think it is always quicker. Mapping takes time and, btw, is superfluous here. Which doesn't mean there are no faster non-lambda solutions — the creation of the stream needs extra time. Nevertheless, the speed advantage for an accustomed solution in the present example should be of a more homeopathic nature. – Kaplan Apr 28 '20 at 17:20
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);
}

- 21
- 5
-
6I would add an if-check in there somewhere, because currently `sum` will call itself infinitely causing this site's host-error ;) (`StackOverflowError`). Something like `int sum(int n){ if(n > 9){ return n%10 + sum(n/10); } return n;}` – Kevin Cruijssen Sep 06 '16 at 14:23
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);
}

- 130
- 1
- 2
- 7
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
}

- 5,970
- 4
- 19
- 39
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.

- 637
- 6
- 15
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;
}

- 306
- 2
- 13
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));

- 474
- 3
- 5
-
2`new Integer(n)` is wasteful. Just call `Integer.toString(n)` or `String.valueOf(n)`. – shmosel Aug 17 '17 at 19:12
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();

- 5,127
- 5
- 23
- 38

- 6,749
- 16
- 58
- 100
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);
}
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;
}

- 503
- 6
- 15
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);

- 1,388
- 23
- 22

- 983
- 9
- 11
-
@saurabhkumar Why do you say doesn't work..? I added screenshots.. – Rohit Kumar Feb 24 '22 at 03:03
-
-
We should not just try to solve it with recursion but also look for optimized ways of solving it. One such option is using tail recursion. Space complexity of recursive algorithms increases when the depth of recursion increases, which can be optimized using tail recursion
public class SumOfDigits {
public int tailRecursiveSumOfDigits(int number, int accumulator)
{
if(number < 10)
return accumulator + number;
else{
int remainder = number % 10;
return tailRecursiveSumOfDigits(number/10, remainder + accumulator);
}
}
public static void main(String[] args)
{
SumOfDigits sod = new SumOfDigits();
System.out.println(sod.tailRecursiveSumOfDigits(1234,0));
}
}

- 700
- 8
- 6
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.

- 4,159
- 9
- 48
- 93
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);
}
}
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);
}
}

- 3,560
- 27
- 33
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);
}
}

- 239
- 2
- 13