1
\$\begingroup\$

I need to find the sum of the digits of the given number and repeat the process until the value lies between 1 to 9.

e.g if the input is 72457 then,

7+2+4+5+7 = 25

2+5 = 7

so , the function should return 7.

Also, if the input is a negative number like -72457 the function should return -7.

Here's what i tried,

int digitSum(int input1){
int flag=0;
if(input1<0)
 flag=1;
 int rem,sum=0;
 int x=abs(input1);
 while(x>0){
 rem=x%10;
 sum+=rem;
 x=x/10;
 }
 int value = sum%9;
 if(value==0){
 if(flag==1)
 return -9;
 else
 return 9; 
 }
 else{
 if(flag==1)
 return -value;
 else
 return value;
 }
}
asked Mar 25, 2019 at 15:33
\$\endgroup\$
3
  • 1
    \$\begingroup\$ What if the input is 0? \$\endgroup\$ Commented Mar 25, 2019 at 16:01
  • \$\begingroup\$ You can shuffle the logic around a bit to simplify this by first having an int which represents the sign of the input number by dividing input / abs(input), which will give you either -1 or 1. Then, during your summation loop, do a comparison of != 0. so that you don't have to worry about the sign. And finish off by returning sum * sign \$\endgroup\$ Commented Mar 25, 2019 at 16:11
  • 1
    \$\begingroup\$ n % 9 gets you most of the way there; you only need to adjust zero results to ±9, and you're done. \$\endgroup\$ Commented Mar 25, 2019 at 16:23

1 Answer 1

1
\$\begingroup\$

A simplified pure numerical function may be:

int digitSum(int input) {
 int n,m,s = input<0 ? -1:1;
 for(n=input*s; n>9; ) {
 for(m=n, n=0; m>0; m/=10)
 n+=m%10;
 }
 return n*s;
}
answered Mar 26, 2019 at 9:19
\$\endgroup\$
1
  • \$\begingroup\$ Thanks, @holger, I missed the recursivness of the problem. \$\endgroup\$ Commented Mar 26, 2019 at 14:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.