在Python中,如何找到整数中的位数?
当前回答
一种快速的解决方案,它使用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)(这非常非常大)就可以工作。
其他回答
如果你必须要求用户输入,然后你必须数出有多少个数字,那么你可以这样做:
count_number = input('Please enter a number\t')
print(len(count_number))
注意:永远不要使用int作为用户输入。
对于整数,可以使用以下方法快速完成:
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
供以后参考。
>>> a=12345
>>> a.__str__().__len__()
5
这里是最简单的方法,不需要将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
正如其他答案所示,使用log10会导致大n的错误结果,而使用len(str(…))或手动循环会导致大n的性能变慢。Jodag的答案提供了一个非常好的替代方案,它只适用于可能会使您的计算机崩溃的整数,但我们可以做得更好,甚至更快(对于n足够小的数学。Log2保证是准确的),避免使用对数,而是使用二进制:
def num_digits(n: int) -> int:
assert n > 0
i = int(0.30102999566398114 * (n.bit_length() - 1)) + 1
return (10 ** i <= n) + i
让我们来分析一下。首先是奇怪的n.bit_length()。这将以二进制形式计算长度:
assert 4 == (0b1111).bit_length()
assert 8 == (0b1011_1000).bit_length()
assert 9 == (0b1_1011_1000).bit_length()
与对数不同,这对于整数来说既快速又精确。结果是,这个结果正好是(log2(n)) + 1。为了单独得到地板(log2(n)),我们减去1,因此n.bit_length() - 1。
接下来,我们乘以0.30102999566398114。这相当于log10(2)稍微舍入。这利用了对数规则,以便从地板(log2(n))计算地板(log10(n))的估计值。
现在,您可能想知道我们在这一点上可能有多差,因为尽管0.30102999566398114 * log2(n) ~ log10(n),但对于floor(0.30102999566398114 * floor(log2(n))) ~ floor(log10(n)),情况并非如此。回想一下x - 1 < floor(x) <= x,我们可以做一些快速的计算:
log2(n) - 1 < floor(log2(n)) <= log2(n)
log10(n) - 0.30102999566398114 < 0.30102999566398114 * floor(log2(n)) <= log10(n)
floor(log10(n) - 0.30102999566398114) < floor(0.30102999566398114 * floor(log2(n))) <= floor(log10(n))
请注意,floor(log10(n) - 0.30102999566398114)至少是floor(log10(n)) - 1,这意味着我们与结果最多相差1。这是最后的修正,我们检查10 ** i <= n,当结果太小时导致额外的1 +,当结果刚刚好时导致0 +。
类似于Jodag的答案,这种方法实际上对非常非常大的n无效,大约在10 ** 2 ** 52左右,其中i的误差超过-1。然而,这种大小的整数可能会使您的计算机崩溃,所以这应该足够了。