-3

Say I have the number 123

Is there a computationally efficient way of adding 1+2+3 and getting the answer back

Ideally I'd avoid division or parsing to String as I feel this can be quite inefficient.

Gabriel Stellini
  • 426
  • 4
  • 13

1 Answers1

1

No need of parsing to string.

int sum=0;
while(n>0)
{
    sum += n%10; // add the last digit
    n/=10;  // remove the last digit.
}
dryairship
  • 6,022
  • 4
  • 28
  • 54