在Python中,如何找到整数中的位数?
当前回答
def count_digit(number):
if number >= 10:
count = 2
else:
count = 1
while number//10 > 9:
count += 1
number = number//10
return count
其他回答
一种快速的解决方案,它使用floor(log10(n))的自我修正实现,基于“更好的方法来计算整数n和b的log(n,b)的floor ?”
import math
def floor_log(n, b):
res = math.floor(math.log(n, b))
c = b**res
return res + (b*c <= n) - (c > n)
def num_digits(n):
return 1 if n == 0 else 1 + floor_log(abs(n), 10)
这非常快,只要n < 10**(2**52)(这非常非常大)就可以工作。
如果你想要一个整数的长度等于这个整数的位数,你总是可以把它转换成字符串,比如str(133),然后像len(str(123))一样找到它的长度。
def length(i):
return len(str(i))
我的代码相同如下,我已经使用了log10方法:
from math import *
def digit_count(数量):
if number>1 and round(log10(number))>=log10(number) and number%10!=0 :
return round(log10(number))
elif number>1 and round(log10(number))<log10(number) and number%10!=0:
return round(log10(number))+1
elif number%10==0 and number!=0:
return int(log10(number)+1)
elif number==1 or number==0:
return 1
我必须在1和0的情况下指定,因为log10(1)=0和log10(0)=ND,因此上面提到的条件不满足。但是,此代码仅适用于整数。
没有导入和str()这样的函数的解决方案
def numlen(num):
result = 1
divider = 10
while num % divider != num:
divider *= 10
result += 1
return result