在Python中,如何找到整数中的位数?
发布于 2010-02-03 13:00:53
如果您希望整数的长度与整数中的位数相同,则始终可以将其转换为像str(133)
这样的字符串,并像len(str(123))
一样找到它的长度。
发布于 2010-02-03 13:04:55
不转换为字符串
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
发布于 2015-03-06 01:17:06
所有的math.log10解决方案都会给你带来问题。
math.log10很快,但是当你的数字大于999999999999997的时候会出问题。这是因为浮点数的.9s太多,导致结果向上舍入。
解决方案是对超过该阈值的数字使用while计数器方法。
为了更快,可以创建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
https://stackoverflow.com/questions/2189800
复制相似问题