在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