How to sum digits of an integer in java?
A simple solution using streams:
int n = 321;
int sum = String.valueOf(n)
.chars()
.map(Character::getNumericValue)
.sum();
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;
}
Recursions are always faster than loops!
Shortest and best:
public static long sumDigits(long i) {
return i == 0 ? 0 : i % 10 + sumDigits(i / 10);
}
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