3 回答

TA貢獻(xiàn)1848條經(jīng)驗 獲得超2個贊
如果您希望整數(shù)的長度與整數(shù)的位數(shù)相同,則始終可以將其轉(zhuǎn)換為string,str(133)
并找到其長度,如len(str(123))
。

TA貢獻(xiàn)1809條經(jīng)驗 獲得超8個贊
不轉(zhuǎn)換為字符串
import math
digits = int(math.log10(n))+1
同時處理零和負(fù)數(shù)
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 '-'
您可能希望將其放入函數(shù)中:)
這是一些基準(zhǔn)。在len(str())已經(jīng)落后的甚至是相當(dāng)小的數(shù)字
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

TA貢獻(xiàn)1783條經(jīng)驗 獲得超4個贊
所有math.log10解決方案都會給您帶來問題。
math.log10速度很快,但是當(dāng)您的數(shù)字大于999999999999997時會出現(xiàn)問題。這是因為float的.9s太多,導(dǎo)致結(jié)果四舍五入。
解決方案是對大于該閾值的數(shù)字使用while計數(shù)器方法。
為了使其更快,請創(chuàng)建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
添加回答
舉報