传统的做法是,不断地除以10,
def digits(n):
cnt = 0
while n:
cnt += 1
n //= 10
return cnt
在微博上看到一种较为数学(也较为tricky)的方法,使用 log10 (以10为底,而) 映射的结果即为该数的位数,
- x=1∼9 : 0<log10x<1
- x=10∼99 : 1<log10x<2
- …
我们只需对其映射结果取整加1即可。我们甚至只需定义一个匿名函数:
from math import log10
digits = lambda n: int(log10(n))+1
举一反三
上文默认都是十进制数,如何判断一个10进制数对应的二进制的位数呢,自然我们用的对数是以2为底的对数: log2
- x=4∼7 : 2<log2(x)<3
- x=10∼15 : 3<log2(x)<4
- …
from math import log2
digits = lambda n: int(log2(n))+1