Sum of Digits of a Number
Last Updated :
07 Feb, 2025
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
Iterative Approach
The idea is to add the digits starting from the rightmost (least significant) digit and moving towards the leftmost (most significant) digit. This can be done by repeatedly extracting the last digit from the number using modulo 10 operation, adding it to the sum, and then removing it using integer division by 10. For eg: n = 1567, then 1567 / 10 = 156.7 = 156(Integer Division).
C++
// Iterative C++ Code to find sum of digits
#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
// Iterative C Code to find sum of digits
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
// Iterative Java Code to find sum of digits
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
# Iterative Python Code to find sum of digits
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#
// Iterative C# Code to find sum of digits
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
// Iterative JavaScript Code to find sum of digits
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;
}
// Driver Code
let n = 12345;
console.log(sumOfDigits(n));
Time Complexity: O(log10n), as we are iterating over all the digits.
Auxiliary Space: O(1)
Recursive Approach
We can also use recursion to find the sum of digits. The idea is to extract the last digit. add it to the sum, and recursively call the function with the remaining number (after removing the last digit).
- Base Case: If the number is 0, return 0.
- Recursive Case: Extract the last digit and add it to the result of recursive call with n / 10.
C++
// Recursive C++ Code to find sum of digits
#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
// Recursive C Code to find sum of digits
#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
// Recursive Java Code to find sum of digits
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
# Recursive Python Code to find sum of digits
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#
// Recursive C# Code to find sum of digits
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
// Recursive JavaScript Code to find sum of digits
function sumOfDigits(n) {
// Base Case
if (n == 0)
return 0;
// Recursive Case
return (n % 10) + sumOfDigits(Math.floor(n / 10));
}
// Driver code
console.log(sumOfDigits(12345));
Time Complexity: O(log10n), as we are iterating over all the digits.
Auxiliary Space: O(log10n) because of function call stack.
The idea is to take the input number as a string and then iterate over all the characters(digits) to find the sum of digits. To find the actual value of a digit from a character, subtract the ASCII value of '0' from the character.
This approach is used when the input number is so large that it cannot be stored in integer data types.
C++
// C++ Code to find the sum of digits by
// taking the input number as string
#include <iostream>
using namespace std;
int sumOfDigits(string &s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
// Extract digit from character
int digit = s[i] - '0';
// Add digit to the sum
sum = sum + digit;
}
return sum;
}
int main() {
string s = "123456789123456789123422";
cout << sumOfDigits(s);
return 0;
}
C
// C Code to find the sum of digits by
// taking the input number as string
#include <string.h>
int sumOfDigits(char *s) {
int sum = 0;
for (int i = 0; i < strlen(s); i++) {
// Extract digit from character
int digit = s[i] - '0';
// Add digit to the sum
sum = sum + digit;
}
return sum;
}
int main() {
char s[] = "123456789123456789123422";
printf("%d", sumOfDigits(s));
return 0;
}
Java
// Java Code to find the sum of digits by
// taking the input number as string
class GfG {
static int sumOfDigits(String s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
// Extract digit from character
int digit = s.charAt(i) - '0';
// Add digit to the sum
sum = sum + digit;
}
return sum;
}
public static void main(String[] args) {
String s = "123456789123456789123422";
System.out.println(sumOfDigits(s));
}
}
Python
# Python Code to find the sum of digits by
# taking the input number as string
def sumOfDigits(s):
sum = 0
for i in range(len(s)):
# Extract digit from character
digit = ord(s[i]) - ord('0')
# Add digit to the sum
sum = sum + digit
return sum
if __name__ == "__main__":
s = "123456789123456789123422"
print(sumOfDigits(s))
C#
// C# Code to find the sum of digits by
// taking the input number as string
using System;
class GfG {
static int sumOfDigits(string s) {
int sum = 0;
for (int i = 0; i < s.Length; i++) {
// Extract digit from character
int digit = s[i] - '0';
// Add digit to the sum
sum = sum + digit;
}
return sum;
}
static void Main() {
string s = "123456789123456789123422";
Console.WriteLine(sumOfDigits(s));
}
}
JavaScript
// JavaScript Code to find the sum of digits by
// taking the input number as string
function sumOfDigits(s) {
let sum = 0;
for (let i = 0; i < s.length; i++) {
// Extract digit from character
let digit = s[i] - '0';
// Add digit to the sum
sum = sum + digit;
}
return sum;
}
// Driver Code
let s = "123456789123456789123422";
console.log(sumOfDigits(s));
Time Complexity: O(len(s)), as we are iterating over all the characters(digits).
Auxiliary Space: O(1)
Similar Reads
Sum of digit of a number using recursion Given a number, we need to find sum of its digits using recursion.Examples: Input: 12345Output: 15Explanation: Sum of digits â 1 + 2 + 3 + 4 + 5 = 15Input: 45632Output: 20 Approach:To understand the algorithm, consider the number 12345 and refer to the illustration below..Extract the last digit: 123
3 min read
Find sum of digits in factorial of a number Given a number n, write code to find the sum of digits in the factorial of the number. Given n ⤠5000 Examples: Input : 10 Output : 27 Input : 100 Output : 648 Recommended PracticeSum of digits in factorial of a numberTry It!It is not possible to store a number as large as 100! under some data types
11 min read
Sum of all N digit palindrome numbers Given a number N. The task is to find the sum of all N-digit palindromes. Examples: Input: N = 2 Output: 495 Explanation: 11 + 22 + 33 + 44 + 55 + 66 + 77 + 88 + 99 = 495 Input: N = 7 Output: 49500000000 Naive Approach:Run a loop from 10^(n-1) to 10^(n) - 1 and check when the current number is palin
7 min read
Sum of an array of large numbers Given an integer K and an array arr[] consisting of N large numbers in the form of strings, the task is to find the sum of all the large numbers of the array. Examples: Input: K = 50, arr[] = {â01234567890123456789012345678901234567890123456789â, â01234567890123456789012345678901234567890123456789â,
10 min read
Sum of digits of a given number to a given power Given a number, we need to find the sum of all the digits of a number which we get after raising the number to a specified power.Examples: Input: number = 5, power = 4 Output: 13 Explanation: Raising 5 to the power 4 we get 625. Now adding all the digits = 6 + 2 + 5 Input: number = 9, power = 5 Outp
3 min read
Check if the sum of digits of a number N divides it Given a number n, the task is to check if the sum of digits of the given number divides the number or not. Examples: Input : n = 12Output : YesExplanation: Sum of digits = 1+2 =3 and 3 divides 12.Input : n = 15Output : NoExplanation: Sum of digits = 1+5 =6 and 15 % 6 != 0.Using Iterative Method - O(
6 min read
Sum of digits equal to a given number in PL/SQL Prerequisite - PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given a number and range and the task is to display all
2 min read
n-th number whose sum of digits is ten Given an integer value n, find out the n-th positive integer whose sum is 10. Examples: Input: n = 2 Output: 28 The first number with sum of digits as 10 is 19. Second number is 28. Input: 15 Output: 154 Method 1 (Simple): We traverse through all numbers. For every number, we find the sum of digits.
8 min read
Count total number of digits from 1 to n Given a number n, count the total number of digits required to write all numbers from 1 to n. Examples: Input : 13 Output : 17 Numbers from 1 to 13 are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13. So 1 - 9 require 9 digits and 10 - 13 require 8 digits. Hence 9 + 8 = 17 digits are required. Input : 4 O
8 min read
Special two digit number A special two-digit number is a number such that when the sum of the digits of the number is added to the product of its digits, the result is equal to the original two-digit number. Examples : input : 59. output : 59 is a Special Two-Digit Number Explanation: Sum of digits = 5 + 9 = 14 Product of i
6 min read