Sum of Digits
Problem
Read an integer and print the sum of its digits. Ignore the minus sign.
Constraints
- -10^18 <= n <= 10^18
Examples
Input
12345
Output
15
Solutions
% 10 gives the last digit and / 10 removes it. We repeat until the number is 0 and add every digit to a running sum.
/*
* Problem : Add all digits of a number.
* Input : One integer.
* Output : The sum of the digits.
* Approach: Take the last digit and remove it, again and again.
* Time : O(d)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
long number = Math.abs(new Scanner(System.in).nextLong());
// Step 1: Start the sum with 0.
int sum = 0;
// Step 2: Repeat until no digits are left.
while (number > 0) {
// Step 3: Take the last digit and add it to the sum. Example: 12345 % 10 = 5.
sum = sum + (int) (number % 10);
// Step 4: Remove the last digit. Example: 12345 / 10 = 1234.
number = number / 10;
}
// Step 5: Print the sum. For the number 0 the loop does not run and the sum stays 0.
System.out.println(sum);
}
}
Hints (2)
- Which operator gives the last digit of a number?
- Which operation removes the last digit?