Problem Statement: Given an integer, find the sum of digits of that integer.
Examples:
Example 1: Input: N = 472 Output: 13 Explanation: The digits in the number are 4,7 and 2. Summing them up gives us a value of 13 Example 2: Input: N = 102 Output: 3 Explanation: The digits in the number are 0, 1, and 2. Summing them up gives us a value of 3
Solution:
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
Intuition: We can see that we somehow need to extract the individual digits of a number and sum them up. Is there any operator that we know of that can be used to extract digits from a number?
Modulus operation(%) : 10%3 = 1(Modulus operation gives us the remainder when we divide a fraction)
Divisor operation(/) : 10/3 = 3(Divisor operation gives us the quotient when we divide a fraction)
Note: Did you notice we get the last digit of a number when we perform a modulus operation with a value of 10
Approach:
- Get the last digit of the number
- Add the last digit to a sum variable
- Divide the number by 10 and repeat the process until the number is not zero
Code:
C++ Code
#include<bits/stdc++.h>
using namespace std;
int getSum(int n)
{
int d,sum=0;
while(n!=0)
{
d=n%10;
sum+=d;
n=n/10;
}
return sum;
}
int main()
{
int n=472;
cout<<"Sum of digits of the given number is "<<getSum(n);
return 0;
}
Output: Sum of digits of the given number is 13
Time Complexity: O(N), N is the no. of digits
Space Complexity: O(1)
Java Code
import java.io.*;
class Test
{
static private int getSum(int n)
{
int d;
int sum = 0;
while (n != 0)
{
d = n % 10;
sum += d;
n = n / 10;
}
return sum;
}
public static void main(String[] args)
{
int n = 472;
System.out.print("Sum of digits of the given number is "+getSum(n));
}
}
Output: Sum of digits of the given number is 13
Time Complexity: O(N), N is the no. of digits
Space Complexity: O(1)
Special thanks to Naman Daga for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article