在Python中,如何找到整数中的位数?


当前回答

对于整数,可以使用以下方法快速完成:

len(str(abs(1234567890)))

获取"1234567890"的绝对值的字符串长度。

abs返回没有任何负号的数字(只有数字的大小),str将其转换为字符串,len返回该字符串的字符串长度。

如果你想让它为浮点数工作,你可以使用以下任何一个:

# Ignore all after decimal place
len(str(abs(0.1234567890)).split(".")[0])

# Ignore just the decimal place
len(str(abs(0.1234567890)))-1

供以后参考。

其他回答

没有导入和str()这样的函数的解决方案

def numlen(num):
    result = 1
    divider = 10
    while num % divider != num:
        divider *= 10
        result += 1
    return result

如果你想要一个整数的长度等于这个整数的位数,你总是可以把它转换成字符串,比如str(133),然后像len(str(123))一样找到它的长度。

设数字为n,则n中的位数为:

math.floor(math.log10(n))+1

注意,这将为+ve个整数< 10e15给出正确答案。除此之外,返回类型的数学的精度限制。Log10开始起作用,结果可能相差1。我可以简单地在后面用len(str(n));这需要O(log(n))时间,相当于10的幂次迭代。

感谢@SetiVolkylany让我注意到这个限制。令人惊讶的是,看似正确的解决方案在实现细节中有警告。

这里是最简单的方法,不需要将int转换为字符串:

假设给出的数字为15位,例如;n = 787878899999999;

n=787878899999999 
n=abs(n) // we are finding absolute value because if the number is negative int to string conversion will produce wrong output

count=0 //we have taken a counter variable which will increment itself till the last digit

while(n):
    n=n//10   /*Here we are removing the last digit of a number...it will remove until 0 digits will left...and we know that while(0) is False*/
    count+=1  /*this counter variable simply increase its value by 1 after deleting a digit from the original number
print(count)   /*when the while loop will become False because n=0, we will simply print the value of counter variable

输入:

n=787878899999999

输出:

15

科学记数法格式,去掉指数:

int("{:.5e}".format(1000000).split("e")[1]) + 1

我不知道速度如何,但很简单。

请注意小数点后的有效数位数(“5”在”。如果5e”将科学记数法的小数部分舍入到另一个数字,则可能会出现问题。我把它设得任意大,但可以反映出你所知道的最大数字的长度。