Create a solution method that takes a natural number N, adds each digit of N, and returns. ** Example) If N = 123, return 1 + 2 + 3 = 6. ** **
--N range: Natural numbers less than 100,000,000
N | answer |
---|---|
123 | 6 |
987 | 24 |
public class Solution {
public int solution(int n) {
//For saving totals
int sum = 0;
while(n > 0) {
sum += n % 10; //Divide by 10 and add the remainder.
n /= 10; //Substitute in n to use the result of division by 10 for the next calculation.
}
return sum;
}
}