在Python中,如何找到整数中的位数?
当前回答
不需要转换为字符串
import math
digits = int(math.log10(n))+1
也可以处理0和负数
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 '-'
你可能想把它放在一个函数中:)
以下是一些基准测试。len(str())对于非常小的数字已经落后了
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
其他回答
不需要转换为字符串
import math
digits = int(math.log10(n))+1
也可以处理0和负数
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 '-'
你可能想把它放在一个函数中:)
以下是一些基准测试。len(str())对于非常小的数字已经落后了
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
计算w/o将整数转换为字符串的位数:
x=123
x=abs(x)
i = 0
while x >= 10**i:
i +=1
# i is the number of digits
设数字为n,则n中的位数为:
math.floor(math.log10(n))+1
注意,这将为+ve个整数< 10e15给出正确答案。除此之外,返回类型的数学的精度限制。Log10开始起作用,结果可能相差1。我可以简单地在后面用len(str(n));这需要O(log(n))时间,相当于10的幂次迭代。
感谢@SetiVolkylany让我注意到这个限制。令人惊讶的是,看似正确的解决方案在实现细节中有警告。
如果你必须要求用户输入,然后你必须数出有多少个数字,那么你可以这样做:
count_number = input('Please enter a number\t')
print(len(count_number))
注意:永远不要使用int作为用户输入。
如果您正在寻找一个不使用内置函数的解决方案。 唯一需要注意的是当你发送a = 000时。
def number_length(a: int) -> int:
length = 0
if a == 0:
return length + 1
else:
while a > 0:
a = a // 10
length += 1
return length
if __name__ == '__main__':
print(number_length(123)
assert number_length(10) == 2
assert number_length(0) == 1
assert number_length(256) == 3
assert number_length(4444) == 4