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


Constraints


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:

By repeating this process in a loop, we can extract all digits from the number and compute the total sum.


Approach

  1. Initialize a variable sum to store the result, starting from 0.

  2. While the number n is greater than 0:

    • Extract the last digit using n % 10.

    • Add it to sum.

    • Remove the last digit using integer division n / 10.

  3. 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:


Time Complexity


Space Complexity


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.