查找数字的总和 [英] Finding the sum of the digits

查看:63
本文介绍了查找数字的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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.

这篇关于查找数字的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆