公告
财富商城
积分规则
提问
发文
2020-04-10 03:52发布
乱世女痞
I have a 5-digit integer, say
int num = 23456;
How to find the sum of its digits?
int sum=0;while(num){sum+=num%10;num/=10;}
Gives a negative answer if num is negative, in C99 anyway.
Is this homework?
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.
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.
最多设置5个标签!
Gives a negative answer if num is negative, in C99 anyway.
Is this homework?
Slightly related: if you want the repeated digit sum, a nice optimization would be:
Followed by the rest of the code.
Use the modulo operation to get the value of the least significant digit:
If the input could be a negative number then it would be a good idea to check for that and invert the sign.