第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python中整數(shù)的長度

Python中整數(shù)的長度

蝴蝶不菲 2019-12-10 09:57:46
在Python中,如何找到整數(shù)位數(shù)?
查看完整描述

3 回答

?
慕尼黑5688855

TA貢獻(xiàn)1848條經(jīng)驗 獲得超2個贊

如果您希望整數(shù)的長度與整數(shù)的位數(shù)相同,則始終可以將其轉(zhuǎn)換為string,str(133)并找到其長度,如len(str(123))


查看完整回答
反對 回復(fù) 2019-12-10
?
海綿寶寶撒

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


查看完整回答
反對 回復(fù) 2019-12-10
?
慕娘9325324

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


查看完整回答
反對 回復(fù) 2019-12-10
  • 3 回答
  • 0 關(guān)注
  • 2241 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號