在Python中,如何找到整数中的位数?
当前回答
这里是最简单的方法,不需要将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
其他回答
设数字为n,则n中的位数为:
math.floor(math.log10(n))+1
注意,这将为+ve个整数< 10e15给出正确答案。除此之外,返回类型的数学的精度限制。Log10开始起作用,结果可能相差1。我可以简单地在后面用len(str(n));这需要O(log(n))时间,相当于10的幂次迭代。
感谢@SetiVolkylany让我注意到这个限制。令人惊讶的是,看似正确的解决方案在实现细节中有警告。
没有导入和str()这样的函数的解决方案
def numlen(num):
result = 1
divider = 10
while num % divider != num:
divider *= 10
result += 1
return result
这个问题已经问了好几年了,但是我已经编写了一个基准测试,其中包含了几种计算整数长度的方法。
def libc_size(i):
return libc.snprintf(buf, 100, c_char_p(b'%i'), i) # equivalent to `return snprintf(buf, 100, "%i", i);`
def str_size(i):
return len(str(i)) # Length of `i` as a string
def math_size(i):
return 1 + math.floor(math.log10(i)) # 1 + floor of log10 of i
def exp_size(i):
return int("{:.5e}".format(i).split("e")[1]) + 1 # e.g. `1e10` -> `10` + 1 -> 11
def mod_size(i):
return len("%i" % i) # Uses string modulo instead of str(i)
def fmt_size(i):
return len("{0}".format(i)) # Same as above but str.format
(libc函数需要一些设置,我没有包括这些设置)
size_exp由Brian Preslopsky提供,size_str由GeekTantra提供,size_math由John La Rooy提供
以下是调查结果:
Time for libc size: 1.2204 μs
Time for string size: 309.41 ns
Time for math size: 329.54 ns
Time for exp size: 1.4902 μs
Time for mod size: 249.36 ns
Time for fmt size: 336.63 ns
In order of speed (fastest first):
+ mod_size (1.000000x)
+ str_size (1.240835x)
+ math_size (1.321577x)
+ fmt_size (1.350007x)
+ libc_size (4.894290x)
+ exp_size (5.976219x)
(声明:函数在输入1到1,000,000上运行)
下面是sys的测试结果。Maxsize: 100000 to sys.maxsize:
Time for libc size: 1.4686 μs
Time for string size: 395.76 ns
Time for math size: 485.94 ns
Time for exp size: 1.6826 μs
Time for mod size: 364.25 ns
Time for fmt size: 453.06 ns
In order of speed (fastest first):
+ mod_size (1.000000x)
+ str_size (1.086498x)
+ fmt_size (1.243817x)
+ math_size (1.334066x)
+ libc_size (4.031780x)
+ exp_size (4.619188x)
正如你所看到的,mod_size (len("%i" %i))是最快的,比使用str(i)略快,比其他方法快得多。
对于整数,可以使用以下方法快速完成:
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
供以后参考。
计算w/o将整数转换为字符串的位数:
x=123
x=abs(x)
i = 0
while x >= 10**i:
i +=1
# i is the number of digits
推荐文章
- 我如何结合两个数据框架?
- 如何计数列表中唯一值的出现
- 为什么Pycharm的检查人员抱怨“d ={}”?
- 如何JSON序列化集?
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?