在Python中,如何找到整数中的位数?
当前回答
from math import log10
digits = lambda n: ((n==0) and 1) or int(log10(abs(n)))+1
其他回答
下面是一个体积大但速度快的版本:
def nbdigit ( x ):
if x >= 10000000000000000 : # 17 -
return len( str( x ))
if x < 100000000 : # 1 - 8
if x < 10000 : # 1 - 4
if x < 100 : return (x >= 10)+1
else : return (x >= 1000)+3
else: # 5 - 8
if x < 1000000 : return (x >= 100000)+5
else : return (x >= 10000000)+7
else: # 9 - 16
if x < 1000000000000 : # 9 - 12
if x < 10000000000 : return (x >= 1000000000)+9
else : return (x >= 100000000000)+11
else: # 13 - 16
if x < 100000000000000 : return (x >= 10000000000000)+13
else : return (x >= 1000000000000000)+15
只有5个比较不是太大的数字。 在我的电脑上,它比数学运算快30%。Log10版本,比len(str())快5%。 好吧……如果你不疯狂地使用它,就没那么吸引人了。
下面是我用来测试/测量我的函数的一组数字:
n = [ int( (i+1)**( 17/7. )) for i in xrange( 1000000 )] + [0,10**16-1,10**16,10**16+1]
注意:它不管理负数,但适应很容易…
coin_digit = str(coin_fark).split(".")[1]
coin_digit_len = len(coin_digit)
print(coin_digit_len)
def digits(n)
count = 0
if n == 0:
return 1
if n < 0:
n *= -1
while (n >= 10**count):
count += 1
n += n%10
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
所有的数学。Log10的解会给你带来问题。
数学。Log10速度很快,但当你的数字大于999999999999997时就会出现问题。这是因为浮点数有太多的.9,导致结果四舍五入。
因此,为了获得最佳性能,对于较小的数字使用math.log,并且只使用超出math.log处理范围的len(str()):
def getIntegerPlaces(theNumber):
if theNumber <= 999999999999997:
return int(math.log10(theNumber)) + 1
else:
return len(str(theNumber))
n = 3566002020360505
count = 0
while(n>0):
count += 1
n = n //10
print(f"The number of digits in the number are: {count}")
output: number中的位数为:16