Sum of Digits of a Number

Last Updated : 2 Apr, 2026

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

Try It Yourself
redirect icon

Using Digit Extraction - O(log10n) Time and O(1) Space

Process digits from right to left by repeatedly taking the last digit using n % 10 which is remainder when divided by 10, adding it to the sum, and then removing it using n / 10 which is floor division with 10.

Dry Run Example

Let’s take n = 1234

  • Start with n = 1234, sum = 0
    Last digit = 1234 % 10 = 4 -> add to sum -> sum = 4
    Remove last digit: n = 1234 / 10 = 123
  • Now n = 123, sum = 4
    Last digit = 123 % 10 = 3 -> add -> sum = 7
    Remove last digit: n = 123 / 10 = 12
  • Now n = 12, sum = 7
    Last digit = 12 % 10 = 2 → add -> sum = 9
    Remove last digit: n = 12 / 10 = 1
  • Now n = 1, sum = 9
    Last digit = 1 % 10 = 1 -> add -> sum = 10
    Remove last digit: n = 1 / 10 = 0
  • Now n = 0, stop.
  • Sum of digits = 10
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
#include<stdio.h>

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;
    printf("%d", sumOfDigits(n));
    return 0;
}
Java
class GfG {
    static 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;
    }

    public static void main(String[] args) {
        int n = 12345;
        System.out.println(sumOfDigits(n));
    }
}
Python
def sumOfDigits(n):
    sum = 0
    while n != 0:

        # Extract the last digit
        last = n % 10

        # Add last digit to sum
        sum += last

        # Remove the last digit
        n //= 10
    return sum

if __name__ == "__main__":
	n = 12345
	print(sumOfDigits(n))
C#
using System;
class GfG {
    static 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;
    }

    static void Main() {
        int n = 12345;
        Console.WriteLine(sumOfDigits(n));
    }
}
JavaScript
function sumOfDigits(n) {
    let sum = 0;
    while (n !== 0) {

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

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

        // Remove the last digit
        n = Math.floor(n / 10);
    }
    return sum;
}

let n = 12345;
console.log(sumOfDigits(n));

Output
15

Using Recursion - O(log10n) Time and O(log10n) Space

Any number can be split into its last digit and the remaining part, i.e., n = (n / 10) * 10 + (n % 10), where n % 10 is the last digit and n / 10 is the remaining number; once take the last digit, the remaining part is just a smaller number with the same problem of finding the sum of its digits, so repeat the same process on it, and keep doing this until the number becomes 0, at which point no digits are left and the process stops.

Dry Run Example

Let’s take n = 1234

  • Start with n = 1234
    We can write it as: (1234 / 10) * 10 + (1234 % 10) = 123 * 10 + 4
    So, last digit = 4, remaining number = 123, Sum = 4
  • Now n = 123
    Write it as: (123 / 10) * 10 + (123 % 10) = 12 * 10 + 3
    Last digit = 3, remaining number = 12, Sum = 4 + 3 = 7
  • Now n = 12
    Write it as: (12 / 10) * 10 + (12 % 10) = 1 * 10 + 2
    Last digit = 2, remaining number = 1, Sum = 7 + 2 = 9
  • Now n = 1
    Write it as: (1 / 10) * 10 + (1 % 10) = 0 * 10 + 1
    Last digit = 1, remaining number = 0, Sum = 9 + 1 = 10
  • Now n = 0, so we stop.
  • Sum of digits = 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
#include <stdio.h>
int sumOfDigits(int n) {
    
    // Base Case 
    if (n == 0)
        return 0;

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

int main() {
    printf("%d", sumOfDigits(12345));
    return 0;
}
Java
import java.io.*;

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

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

    public static void main(String[] args) {
        System.out.println(sumOfDigits(12345));
    }
}
Python
def sumOfDigits(n):
    # Base Case
    if n == 0:
        return 0
  
    # Recursive Case
    return n % 10 + sumOfDigits(n // 10)

if __name__ == "__main__":
    print(sumOfDigits(12345))
C#
using System;

class GfG {
    static int sumOfDigits(int n) {
        
        // Base Case
        if(n == 0)
            return 0;
      
        // Recursive Case
        return n % 10 + sumOfDigits(n / 10);
    }

    static void Main() {
        Console.Write(sumOfDigits(12345));
    }
}
JavaScript
function sumOfDigits(n) {
    
    // Base Case
    if (n == 0)
        return 0;

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

console.log(sumOfDigits(12345));

Output
15

Using String Conversion

A number is made up of digits, and when convert it into a string, each digit becomes a character that can be accessed directly by going through each character one by one and converting it back to a digit,

Let’s take n = 1234

  • Convert number to string → "1234"
  • Start with first character '1'
    Convert to digit -> Sum = 1
  • Move to next character '2'
    Convert to digit -> 2, Sum = 1 + 2 = 3
  • Next character '3'
    Convert to digit -> 3, Sum = 3 + 3 = 6
  • Next character '4'
    Convert to digit -> 4, sum = 6 + 4 = 10
  • No more characters left -> stop
  • Sum of digits = 10

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
#include <stdio.h>
#include <string.h>

int sumOfDigits(int n) {
    
    // Convert number to string
    char s[20];
    sprintf(s, "%d", n);
    int sum = 0;

    // Loop through each character, convert
    // to digit, and add to sum
    for (int i = 0; i < strlen(s); i++) {
        sum += s[i] - '0';
    }

    return sum;
}

int main() {
    int n = 12345;
    printf("%d\n", sumOfDigits(n));
    return 0;
}
Java
class GfG {
    
    // Function to calculate sum of digits 
    // using string conversion
    static int sumOfDigits(int n) {
        
        // Convert number to string
        String s = Integer.toString(n);
        int sum = 0;

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

        return sum;
    }

    public static void main(String[] args) {
        int n = 12345;
        System.out.println(sumOfDigits(n));
    }
}
Python
def sumOfDigits(n):
    
    # Convert number to string
    s = str(n)
    sum = 0

    # Loop through each character, convert 
    # to digit, and add to sum
    for ch in s:
        sum += int(ch)

    return sum

n = 12345
print(sumOfDigits(n))
C#
using System;

class GfG
{
    // Function to calculate sum of digits
    // using string conversion
    public static int sumOfDigits(int n)
    {
        // Convert number to string
        string s = n.ToString();
        int sum = 0;

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

        return sum;
    }

    public static void Main()
    {
        int n = 12345;
        Console.WriteLine(sumOfDigits(n));
    }
}
JavaScript
function sumOfDigits(n) {
    
    // Convert number to string
    let s = n.toString();
    let sum = 0;

    // Loop through each character, convert 
    // to digit, and add to sum
    for (let ch of s) {
        sum += parseInt(ch);
    }

    return sum;
}

// Driver Code
let n = 12345;
console.log(sumOfDigits(n));

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.

Comment