查找数字的总和
问题描述:
我有一个5位整数,例如
I have a 5-digit integer, say
int num = 23456;
如何查找其数字的总和?
How to find the sum of its digits?
答
使用取模运算来获取最低有效数字的值:
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.