(Translated by https://www.hiragana.jp/)
Sum of Digits of a Number - GeeksforGeeks
Open In App

Sum of Digits of a Number

Last Updated : 14 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number n, find the sum of its digits.

Examples : 

Input: n = 687
Output: 21
Explanation: The sum of its digits are: 6 + 8 + 7 = 21

Input: n = 12
Output: 3
Explanation: The sum of its digits are: 1 + 2 = 3

[Approach 1] Digit Extraction - O(log10n) Time and O(1) Space

We can sum the digits of a number by repeatedly extracting the last digit using n % 10, adding it to the sum, and then removing it by dividing n by 10 using integer division.

C++
#include <iostream>
using namespace std;

int sumOfDigits(int n) {
    int sum = 0;
    while (n != 0) {

        // Extract the last digit
        int last = n % 10;

        // Add last digit to sum
        sum += last;

        // Remove the last digit
        n /= 10;
    }
    return sum;
}

int main() {
    int n = 12345;
    cout << sumOfDigits(n);
    return 0;
}
C Java Python C# JavaScript

Output
15

[Approach 2] Using Recursion - O(log10n) Time and O(log10n) Space

We can use recursion to find the sum of digits. The idea is to extract the last digit, add it to the sum of digits of the remaining number, and repeat.
Base Case: If the number is 0, return 0.
Recursive Case: Return (n % 10) + sumOfDig(n / 10)

C++
#include <iostream>
using namespace std;

int sumOfDigits(int n) {
    
    // Base Case
    if (n == 0)
        return 0;

    // Recursive Case
    return (n % 10) + sumOfDigits(n / 10);
}

int main() {
    cout << sumOfDigits(12345);
    return 0;
}
C Java Python C# JavaScript

Output
15

[Approach 3] String Conversion

Convert the number to a string and iterate through each character (digit). For each character, subtract the ASCII value of '0' to get the actual digit, then add it to the sum.

Note: This method is especially useful when the number is too large to fit in standard integer types.

C++
#include <iostream>
#include <string>
using namespace std;

// Function to calculate sum of digits using string conversion

int sumOfDigits(int n) {
    // Convert number to string
    string s = to_string(n);  
    int sum = 0;

    // Loop through each character, convert to digit, and add to sum
    for (char ch : s) {
        sum += ch - '0';
    }
    return sum;
}

int main() {
    int n = 12345;
    cout << sumOfDigits(n) << endl;
    return 0;
}
C Java Python C# JavaScript

Output
15

Time Complexity: O(d) – we iterate over each of the d digits, where d ≈ log₁₀(n) (count of digits)
Auxiliary Space: O(d) - to store all d digits as characters.


Program to Find the Sum of All Digits of a Number
Article Tags :

Similar Reads