Given a number n find sum of All Digits in n
Problem Link : Given a number n find the sum of All Digits in n
Problem Statement
Given an integer n, find the sum of its digits.
Examples
-
Input:
n = 12
Output:3
Explanation: 1 + 2 = 3 -
Input:
n = 23
Output:5
Explanation: 2 + 3 = 5
Constraints
1 ≤ n ≤ 10^5
Intuition
Every number is composed of digits in place values (units, tens, hundreds, etc.). To compute the sum of these digits, we need to isolate each digit one at a time and accumulate their sum.
This can be efficiently achieved using modulus and division operations:
-
n % 10gives the last digit -
n / 10removes the last digit
By repeating this process in a loop, we can extract all digits from the number and compute the total sum.
Approach
-
Initialize a variable
sumto store the result, starting from 0. -
While the number
nis greater than 0:-
Extract the last digit using
n % 10. -
Add it to
sum. -
Remove the last digit using integer division
n / 10.
-
-
Return the final value of
sum.
Java Code
class Solution {
static int sumOfDigits(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10; // Extract last digit
sum += r; // Add digit to sum
n /= 10; // Remove last digit
}
return sum;
}
}
Dry Run
Let’s dry run with n = 432:
-
Initialize:
sum = 0 -
Loop:
-
r = 432 % 10 = 2→sum = 0 + 2 = 2→n = 432 / 10 = 43 -
r = 43 % 10 = 3→sum = 2 + 3 = 5→n = 43 / 10 = 4 -
r = 4 % 10 = 4→sum = 5 + 4 = 9→n = 4 / 10 = 0
-
-
End of loop → Return
sum = 9
Time Complexity
-
O(log₁₀(n))
-
At each step, we remove one digit from
n. -
A number with
ddigits will run the loopdtimes. -
For
n <= 10^5, the maximum number of digits is 6.
-
Space Complexity
-
O(1)
- We use a constant amount of space regardless of the input size.
Conclusion
This is a classic and efficient approach for summing digits of a number using basic mathematical operations. It performs well within the given constraints and has optimal time and space complexity.