在Python中,如何找到整数中的位数?
当前回答
Python 2。* int需要4或8字节(32或64位),这取决于你的Python版本。sys。Maxint(2**31-1用于32位int, 2**63-1用于64位int)将告诉您两种可能性中哪一种获得。
在Python 3中,int(就像Python 2中的long)可以取任意大小,直到可用内存的数量;sys。Getsizeof为任何给定值提供了一个很好的指示,尽管它也计算了一些固定开销:
>>> import sys
>>> sys.getsizeof(0)
12
>>> sys.getsizeof(2**99)
28
如果像其他答案所建议的那样,您正在考虑整数值的某个字符串表示,那么只需取该表示的len,以10为基底或以其他方式!
其他回答
这是另一种计算任何数字的小数点前的位数的方法
from math import fabs
len(format(fabs(100),".0f"))
Out[102]: 3
len(format(fabs(1e10),".0f"))
Out[165]: 11
len(format(fabs(1235.4576),".0f"))
Out[166]: 4
我做了一个简短的基准测试,进行了10,000次循环
num len(str(num)) ---- len(format(fabs(num),".0f")) ---- speed-up
2**1e0 2.179400e-07 sec ---- 8.577000e-07 sec ---- 0.2541
2**1e1 2.396900e-07 sec ---- 8.668800e-07 sec ---- 0.2765
2**1e2 9.587700e-07 sec ---- 1.330370e-06 sec ---- 0.7207
2**1e3 2.321700e-06 sec ---- 1.761305e-05 sec ---- 0.1318
这是一个较慢但更简单的选择。
但是即使这个解也会给出错误的99999999999998
len(format(fabs(9999999999999998),".0f"))
Out[146]: 16
len(format(fabs(9999999999999999),".0f"))
Out[145]: 17
对于子孙后代来说,这无疑是迄今为止解决这个问题最慢的方法:
def num_digits(num, number_of_calls=1):
"Returns the number of digits of an integer num."
if num == 0 or num == -1:
return 1 if number_of_calls == 1 else 0
else:
return 1 + num_digits(num/10, number_of_calls+1)
如果你必须要求用户输入,然后你必须数出有多少个数字,那么你可以这样做:
count_number = input('Please enter a number\t')
print(len(count_number))
注意:永远不要使用int作为用户输入。
这里是最简单的方法,不需要将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的解会给你带来问题。
数学。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))