正整数位和的模数使用函数?

时间:2013-06-09 00:44:48

标签: function python-3.x module

我创建了一个函数,它对给定正整数的数字求和:

def digit_sum(n):
    tot = 0
    for i in str(n):
        tot += int(i)
    return tot

但我知道使用mod10,mod 100等你可以找到给定数字的数字。所以我认为有一种替代方法来构造函数而不需要前后整数转换。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

此处显示的是Javascript:http://jsfiddle.net/bhQLa/

使用

分别打破数字
// Loop through the digits without using string
var base = 1;
while (base * 10 <= num) base *= 10;
while (base >= 1) {
    var digit = (num - (num % base)) / base;
    digits.push(digit);
    num -= digit * base;
    base /= 10;
}
// ---

然后总结一下。首先将基数增加到最大值。然后在抓取数字(num - (num % base)) / base后递减基数。不要忘记减少你的工作号码,然后是基数。

相关问题