Sum of Digits

beginner Number Problems

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

Best approachTime O(d)Space O(1)

% 10 gives the last digit and / 10 removes it. We repeat until the number is 0 and add every digit to a running sum.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * 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)
  1. Which operator gives the last digit of a number?
  2. Which operation removes the last digit?