Python中整数的长度

2024-04-20 01:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

如果您希望整数的长度与整数中的位数相同,则始终可以将其转换为类似于str(133)的字符串,并找到类似于len(str(123))的长度。

所有的math.log10解决方案都会给你带来问题

math.log10很快,但当您的数字大于99999999999 7时会出现问题。这是因为浮点有太多的.9,导致结果向上舍入。

解决方法是对高于该阈值的数字使用while counter方法。

为了使这个过程更快,可以创建10^16、10^17等等,并将其作为变量存储在列表中。这样,它就像一个表查找。

def getIntegerPlaces(theNumber):
    if theNumber <= 999999999999997:
        return int(math.log10(theNumber)) + 1
    else:
        counter = 15
        while theNumber >= 10**counter:
            counter += 1
        return counter

不转换为字符串

import math
digits = int(math.log10(n))+1

同时处理零和负数

import math
if n > 0:
    digits = int(math.log10(n))+1
elif n == 0:
    digits = 1
else:
    digits = int(math.log10(-n))+2 # +1 if you don't count the '-' 

你可能想把它放到函数中:)

以下是一些基准。即使是很小的数字,len(str())也已经落后了

timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop

timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
 timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop

timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop

相关问题 更多 >