Easy 0 solved 0% acceptance

Sum of Digits

Add up the decimal digits of a positive integer.

What you'll learn

  • Peel off the last digit with % 10 and drop it with // 10
  • Repeat a step until a number reaches zero
  • Keep a running total

Problem

Add up every decimal digit of n. For 352 the digits are 3, 5 and 2.

Implement sum_of_digits(n).

Input

n: A positive integer.

Output

Return the sum of its digits.

Constraints

1 ≤ n ≤ 10¹⁸

Examples

Example 1
Input:
n = 352

Expected output:
expected = 10
Input:
long long n = 352;

Expected output:
long long expected = 10;
Input:
long n = 352;

Expected output:
long expected = 10;

Explanation

3 + 5 + 2 = 10.

Example 2
Input:
n = 1000

Expected output:
expected = 1
Input:
long long n = 1000;

Expected output:
long long expected = 1;
Input:
long n = 1000;

Expected output:
long expected = 1;

Explanation

1 + 0 + 0 + 0 = 1.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Each step only needs the current last digit and the remaining prefix.

Hint 2

Repeatedly peel off digits with division and remainder, or iterate through a string representation.

Hint 3

Make sure single-digit inputs return that digit unchanged.

Expected complexity

O(d) time, O(1) extra space

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.