Sum of Digits of a Number
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 = 21Input: n = 12
Output: 3
Explanation: The sum of its digits are: 1 + 2 = 3
Table of Content
[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 dividingn
by 10 using integer division.
#include <iostream>
using namespace std;
int sumOfDig(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 << sumOfDig(n);
return 0;
}
#include<stdio.h>
int sumOfDig(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", sumOfDig(n));
return 0;
}
class GfG {
static int sumOfDig(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(sumOfDig(n));
}
}
def sumOfDig(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(sumOfDig(n))
using System;
class GfG {
static int sumOfDig(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(sumOfDig(n));
}
}
function sumOfDig(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(sumOfDig(n));
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)
#include <iostream>
using namespace std;
int sumOfDig(int n) {
// Base Case
if (n == 0)
return 0;
// Recursive Case
return (n % 10) + sumOfDig(n / 10);
}
int main() {
cout << sumOfDig(12345);
return 0;
}
#include <stdio.h>
int sumOfDig(int n) {
// Base Case
if (n == 0)
return 0;
// Recursive Case
return (n % 10) + sumOfDig(n / 10);
}
int main() {
printf("%d", sumOfDig(12345));
return 0;
}
import java.io.*;
class GfG {
static int sumOfDig(int n) {
// Base Case
if (n == 0)
return 0;
// Recursive Case
return (n % 10) + sumOfDig(n / 10);
}
public static void main(String[] args) {
System.out.println(sumOfDig(12345));
}
}
def sumOfDig(n):
# Base Case
if n == 0:
return 0
# Recursive Case
return n % 10 + sumOfDig(n // 10)
if __name__ == "__main__":
print(sumOfDig(12345))
using System;
class GfG {
static int sumOfDig(int n) {
// Base Case
if(n == 0)
return 0;
// Recursive Case
return n % 10 + sumOfDig(n / 10);
}
static void Main() {
Console.Write(sumOfDig(12345));
}
}
function sumOfDig(n) {
// Base Case
if (n == 0)
return 0;
// Recursive Case
return (n % 10) + sumOfDig(Math.floor(n / 10));
}
console.log(sumOfDig(12345));
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.
#include <iostream>
#include <string>
using namespace std;
// Function to calculate sum of digits using string conversion
int sumOfDig(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 << sumOfDig(n) << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
// Function to calculate sum of digits using string conversion
int sumOfDig(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", sumOfDig(n));
return 0;
}
class GfG {
// Function to calculate sum of digits using string conversion
static int sumOfDig(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(sumOfDig(n));
}
}
# Function to calculate sum of digits using string conversion
def sumOfDig(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(sumOfDig(n))
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));
}
}
function sumOfDig(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;
}
let n = 12345;
console.log(sumOfDig(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.