Sum of Digits
Given a non-negative integer n, compute the sum of its individual digits. For example, if n is 123, the digits are 1, 2, and 3, and their sum is 6.
The input is a single integer that can range from 0 to 10^9. Zero is a valid input, and its digit sum is 0. Negative numbers are not passed, so you do not need to handle negative inputs.
This problem teaches you how to decompose a number digit by digit using the modulo and division operations. The modulo operator (n % 10) extracts the last digit, while integer division by 10 (n / 10 or n // 10) removes that digit so you can continue with the rest. This technique of repeatedly peeling off digits is fundamental to many number-based problems, including palindrome checks, reverse-integer, and other digit-manipulation tasks.
An alternative approach is to convert the number to a string and iterate over each character, converting back to an integer and summing. While this works, the modulo-and-divide method is more efficient and avoids the overhead of string conversion. It also demonstrates a core pattern used in low-level programming where numbers are manipulated directly.
Edge cases include n = 0, where the sum is 0 (the loop body never executes), and large numbers like 999,999,999 where the sum fits comfortably within a 32-bit integer.
Example Input & Output
1+2+3=6
9+9+9=27
1+0+0+1=2
Sum of digits of 0
4+5+6+7+8=30
Algorithm Flow

Solution Approach
The most efficient approach is to repeatedly extract the last digit using modulo 10 and divide the number by 10 to remove that digit, accumulating the sum in a variable.
The algorithm works as follows: start with s = 0. While n is greater than 0, add n % 10 (the last digit) to s, then divide n by 10 (discarding the last digit). When n reaches 0, all digits have been processed and s contains the total sum. For n = 0, the loop does not execute and s remains 0, which is the correct answer.
The time complexity is O(log n), since the number of iterations equals the number of digits in n (about log�₀ n). The space complexity is O(1), using only a single integer variable. This makes it optimal for any input size.
The string-based alternative — converting n to a string, splitting into characters, and summing their integer values — is also valid but slightly slower due to the conversion overhead. The modulo approach is preferred in competitive programming and technical interviews for its efficiency and low-level elegance.
Best Answers
class Solution {
public int solution(int n) {
int s=0;while(n>0){s+=n%10;n/=10;}return s;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
