C#中的数字总和 [英] Sum of digits in C#

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

问题描述

计算数字和的最快和最容易阅读的实现是什么?

What's the fastest and easiest to read implementation of calculating the sum of digits?

即给定数字:17463 = 1 + 7 + 4 + 6 + 3 = 21

I.e. Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21

推荐答案

你可以用算术来完成,而无需使用字符串:

You could do it arithmetically, without using a string:

sum = 0;
while (n != 0) {
    sum += n % 10;
    n /= 10;
}

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

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