首页 > 后端开发 > Python教程 > 对数字进行求和的最有效方法是什么?

对数字进行求和的最有效方法是什么?

Barbara Streisand
发布: 2024-11-24 01:00:11
原创
437 人浏览过

What's the Most Efficient Way to Sum a Number's Digits?

对数字的数字求和:一种有效的方法

要找到数字中的数字之和,最有效的方法是利用纯整数运算。以下 Python 代码展示了这种技术:

def sum_digits(n):
    s = 0
    while n:
        s += n % 10
        n //= 10
    return s
登录后复制

这里,我们重复应用模 10 来提取最右边的数字并将其添加到总和中。通过整数除以 10,我们转移到下一个数字。

更快的版本使用单个赋值语句:

def sum_digits3(n):
    r = 0
    while n:
        r, n = r + n % 10, n // 10
    return r
登录后复制

速度比较表明使用整数运算明显快于将数字转换为字符串并使用字符串操作。

%timeit sum_digits(n)  # Pure integer operations
1000000 loops, best of 3: 479 ns per loop

%timeit sum_digits2(n)  # Integer operations with divmod
1000000 loops, best of 3: 716 ns per loop

%timeit sum(map(int, str(n)))  # String manipulation
1000000 loops, best of 3: 1.42 us per loop

%timeit sum([int(digit) for digit in str(n)])  # List comprehension
100000 loops, best of 3: 1.52 us per loop

%timeit sum(int(digit) for digit in str(n))  # Generator expression
100000 loops, best of 3: 2.04 us per loop
登录后复制

因此,利用整数运算是对数字求和的最有效方法一个数字。

以上是对数字进行求和的最有效方法是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板