在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
其他回答
如果你必须要求用户输入,然后你必须数出有多少个数字,那么你可以这样做:
count_number = input('Please enter a number\t')
print(len(count_number))
注意:永远不要使用int作为用户输入。
def count_digit(number):
if number >= 10:
count = 2
else:
count = 1
while number//10 > 9:
count += 1
number = number//10
return count
这里是最简单的方法,不需要将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
from math import log10
digits = lambda n: ((n==0) and 1) or int(log10(abs(n)))+1
没有导入和str()这样的函数的解决方案
def numlen(num):
result = 1
divider = 10
while num % divider != num:
divider *= 10
result += 1
return result
推荐文章
- Python 3.7数据类中的类继承
- 如何在PyTorch中初始化权重?
- 计数唯一的值在一列熊猫数据框架像在Qlik?
- 使用Pandas将列转换为行
- 从matplotlib中的颜色映射中获取单个颜色
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异