Repeatedly add all its digits until the result has only one digit.
Example:
Input:38
Output: 2 Explanation: The process is like:3 + 8 = 11
,1 + 1 = 2
. Since2
has only one digit, return it.
Approach
Java
public class AddDigits {
public static void main(String[] args) {
int num = 38;
int sum = addDigits(num);
System.out.println(sum);
}
// method to add digit and get single digit
public static int addDigits(int num) {
// iterate till num>9
while (num > 9) {
int sum = 0;
// iterate till 0 and sum of
// all digit
while (num > 0) {
int mod = num % 10;
sum += mod;
num /= 10;
}
num = sum;
}
return num;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to find adddgits
//till we get the single
//digit
int addDigits(int num)
{
int x=0,n;
while(true)
{
x=0;
n=num;
while(num)
{
x+=num%10;
num=num/10;
}
if(x==n)
break;
num=x;
}
return x;
}
int main()
{
int n=38;
cout<<addDigits(n);
return 0;
}
No comments:
Post a Comment