Given a number, find sum of its digits.
Examples :
Input : n = 687
Output : 21
Input : n = 12
Output : 3
General Algorithm for sum of digits in a given number:
- Get the number
- Declare a variable to store the sum and set it to 0
- Repeat the next two steps till the number is not 0
- Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum.
- Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.
- Print or return the sum
Below are the solutions to get sum of the digits.
1. Iterative:
C++
#include <iostream>
using namespace std;
class gfg {
public :
int getSum( int n)
{
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
};
int main()
{
gfg g;
int n = 687;
cout << g.getSum(n);
return 0;
}
|
C
#include <stdio.h>
int getSum( int n)
{
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
int main()
{
int n = 687;
printf ( " %d " , getSum(n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int getSum( int n)
{
int sum = 0 ;
while (n != 0 ) {
sum = sum + n % 10 ;
n = n / 10 ;
}
return sum;
}
public static void main(String[] args)
{
int n = 687 ;
System.out.println(getSum(n));
}
}
|
Python3
def getSum(n):
sum = 0
while (n ! = 0 ):
sum = sum + int (n % 10 )
n = int (n / 10 )
return sum
n = 687
print (getSum(n))
|
C#
using System;
class GFG {
static int getSum( int n)
{
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
public static void Main()
{
int n = 687;
Console.Write(getSum(n));
}
}
|
PHP
<?php
function getsum( $n )
{
$sum = 0;
while ( $n != 0)
{
$sum = $sum + $n % 10;
$n = $n /10;
}
return $sum ;
}
$n = 687;
$res = getsum( $n );
echo ( "$res" );
?>
|
How to compute in a single line?
Below function has three lines instead of one line but it calculates sum in line. It can be made one line function if we pass pointer to sum.
C++
#include <iostream>
using namespace std;
class gfg {
public :
int getSum( int n)
{
int sum;
for (sum = 0; n > 0; sum += n % 10, n /= 10)
;
return sum;
}
};
int main()
{
gfg g;
int n = 687;
cout << g.getSum(n);
return 0;
}
|
C
#include <stdio.h>
int getSum( int n)
{
int sum;
for (sum = 0; n > 0; sum += n % 10, n /= 10)
;
return sum;
}
int main()
{
int n = 687;
printf ( " %d " , getSum(n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int getSum( int n)
{
int sum;
for (sum = 0 ; n > 0 ; sum += n % 10 , n /= 10 )
;
return sum;
}
public static void main(String[] args)
{
int n = 687 ;
System.out.println(getSum(n));
}
}
|
Python3
def getSum(n):
sum = 0
while (n > 0 ):
sum + = int (n % 10 )
n = int (n / 10 )
return sum
n = 687
print (getSum(n))
|
C#
using System;
class GFG {
static int getSum( int n)
{
int sum;
for (sum = 0; n > 0; sum += n % 10, n /= 10)
;
return sum;
}
public static void Main()
{
int n = 687;
Console.Write(getSum(n));
}
}
|
PHP
<?php
function getsum( $n )
{
for ( $sum = 0; $n > 0; $sum += $n % 10,
$n /= 10);
return $sum ;
}
$n = 687;
echo (getsum( $n ));
?>
|
2. Recursive
Thanks to ayesha for providing the below recursive solution.
C++
#include <iostream>
using namespace std;
class gfg {
public :
int sumDigits( int no)
{
return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
}
};
int main( void )
{
gfg g;
cout << g.sumDigits(687);
return 0;
}
|
C
#include <stdio.h>
using namespace std;
int sumDigits( int no)
{
return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
}
int main( void )
{
printf ( "%d" , sumDigits(687));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int sumDigits( int no)
{
return no == 0 ? 0 : no % 10 + sumDigits(no / 10 );
}
public static void main(String[] args)
{
System.out.println(sumDigits( 687 ));
}
}
|
Python3
def sumDigits(no):
return 0 if no = = 0 else int (no % 10 ) + sumDigits( int (no / 10 ))
print (sumDigits( 687 ))
|
C#
using System;
class GFG {
static int sumDigits( int no)
{
return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
}
public static void Main()
{
Console.Write(sumDigits(687));
}
}
|
PHP
<?php
function sumDigits( $no )
{
return $no == 0 ? 0 : $no % 10 +
sumDigits( $no / 10) ;
}
echo sumDigits(687);
?>
|
3.Taking input as String
When the number of digits of that number exceeds 1019 , we can’t take that number as integer since the range of long long int doesn’t satisfy the given number. So take input as a string, run a loop from start to the length of the string and increase the sum with that character(in this case it is numeric)
Below is the implementation of the above approach
C++14
#include <iostream>
using namespace std;
int getSum(string str)
{
int sum = 0;
for ( int i = 0; i < str.length(); i++) {
sum = sum + str[i] - 48;
}
return sum;
}
int main()
{
string st = "123456789123456789123422" ;
cout << getSum(st);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int getSum(String str)
{
int sum = 0 ;
for ( int i = 0 ; i < str.length(); i++) {
sum = sum + str.charAt(i) - 48 ;
}
return sum;
}
public static void main(String[] args)
{
String st = "123456789123456789123422" ;
System.out.print(getSum(st));
}
}
|
Python3
def getSum(n):
sum = 0
for i in n:
sum = sum + int (i)
return sum
n = "123456789123456789123422"
print (getSum(n))
|
C#
using System;
public class GFG {
static int getSum(String str)
{
int sum = 0;
for ( int i = 0; i < str.Length; i++) {
sum = sum + str[i] - 48;
}
return sum;
}
static public void Main()
{
String st = "123456789123456789123422" ;
Console.Write(getSum(st));
}
}
|
4. Using Tail Recursion
This problem can also be solved using Tail Recursion. Here is approach to solve it.
1. Add another variable “val” to the function and initialize it to ( val = 0 )
2. On every call to the function add the mod value (n%10) to the variable as “(n%10)+val” which is the last digit in n. Along with pass the variable n as n/10.
3. So on the First call it will have the last digit. As we are passing n/10 as n, It follows until n is reduced to single digit.
4. n<10 is the base case so When n < 10, then add the n to the variable as it is the last digit and return the val which will have the sum of digits
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class sum_of_digits {
static int sum_of_digit( int n, int val)
{
if (n < 10 ) {
val = val + n;
return val;
}
return sum_of_digit(n / 10 , (n % 10 ) + val);
}
public static void main(String args[])
{
int num = 12345 ;
int result = sum_of_digit(num, 0 );
System.out.println( "Sum of digits is " + result);
}
}
|
Output
Sum of digits is 15
Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.