Ztude
Ztude

Reputation: 13

how to calculate digits of a number without the right digit

I'm trying to summarize digits of a number with out the right digit in recursion. For example, if the input is 1234, the output should be 6 (1+2+3). If the input is only 1 digit number then the function should return 0.

I'm not sure how can i do both: calculating the digits, remove the last digit from the result AND if the input is a digit number then it should return 0 as well. My code below summarizing all the digits except the left digit. if i try to use a revNum function then for the number '100' for example, the result is 0 instead of 1. Need any1s assistance please :)

int main()
{
    int num = 1234;
    cout << partSum(num);
}
int sumDigits(int num)
{
    if (num<10)
        return 0;
    return num%10 + sumDigits(num / 10);
}

Output should be : 6

Upvotes: 1

Views: 152

Answers (4)

גלעד ברקן
גלעד ברקן

Reputation: 23955

This is a bit of a hack for positive numbers. To get a pure recursion, one way is to inform calls that they are not the first call by marking num somehow, in this case by turning it negative.

JavaScript code:

function sumDigits(num){
  if (num == 0)
    return 0;
      
  if (num < 0){
    if (num > -10)
      return num;
    else
      return num % 10 + sumDigits(~~(num / 10));
        
  } else {
     return -sumDigits(~~(-num/10));
  }
}

console.log(sumDigits(1234));

Upvotes: 0

mdatsev
mdatsev

Reputation: 3879

The function sumDigits should sum the digits and the function partSum just sums the digit of the number divided by 10 (removing the last digit)

int sumDigits(int num)
{
  if (num<10)
    return num;
  return num%10 + sumDigits(num / 10);
}

int partSum(int num)
{
  return sumDigits(num/10);
}

int main()
{
  int num = 1234;
  cout << partSum(num);
}

Upvotes: 2

Mohsen_Fatemi
Mohsen_Fatemi

Reputation: 3391

sumDigits(n/10) will remove the right digit, but you need to modify the function and return num; instead of return 0;

int sumDigits(int num)
{
    if (num<10)
        return num;
    return num%10 + sumDigits(num / 10);
}

int main()
{
    int num = 1234;
    cout << sumDigits(num/10);
}

Upvotes: 1

rustyx
rustyx

Reputation: 85361

Something like this you mean? Note that you don't need recursion.

int sumDigits(int num)
{
  int sum = 0;
  while (num != 0) {
    sum += num % 10;
    num /= 10;
  }
  return sum;
}

int main()
{
  int num = 1234;
  cout << sumDigits(num / 10);
}

Upvotes: 0

Related Questions