Finding the sum of the digits

2020-04-10 03:52发布

I have a 5-digit integer, say

int num = 23456;

How to find the sum of its digits?

标签: c algorithm math
9条回答
forever°为你锁心
2楼-- · 2020-04-10 04:56
int sum=0;while(num){sum+=num%10;num/=10;}

Gives a negative answer if num is negative, in C99 anyway.

Is this homework?

查看更多
SAY GOODBYE
3楼-- · 2020-04-10 04:57

Slightly related: if you want the repeated digit sum, a nice optimization would be:

if (num%3==0) return (num%9==0) ? 9 : 3;

Followed by the rest of the code.

查看更多
Rolldiameter
4楼-- · 2020-04-10 04:58

Use the modulo operation to get the value of the least significant digit:

int num = 23456;
int total = 0;
while (num != 0) {
    total += num % 10;
    num /= 10;
}

If the input could be a negative number then it would be a good idea to check for that and invert the sign.

查看更多
登录 后发表回答