在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让我注意到这个限制。令人惊讶的是,看似正确的解决方案在实现细节中有警告。

如果您正在寻找一个不使用内置函数的解决方案。 唯一需要注意的是当你发送a = 000时。

def number_length(a: int) -> int:
    length = 0
    if a == 0:
        return length + 1
    else:
        while a > 0:
            a = a // 10
            length += 1
        return length
    

if __name__ == '__main__':
    print(number_length(123)
    assert number_length(10) == 2
    assert number_length(0) == 1
    assert number_length(256) == 3
    assert number_length(4444) == 4
def length(i):
  return len(str(i))

一种快速的解决方案,它使用floor(log10(n))的自我修正实现,基于“更好的方法来计算整数n和b的log(n,b)的floor ?”

import math

def floor_log(n, b):
    res = math.floor(math.log(n, b))
    c = b**res
    return res + (b*c <= n) - (c > n)

def num_digits(n):
    return 1 if n == 0 else 1 + floor_log(abs(n), 10)

这非常快,只要n < 10**(2**52)(这非常非常大)就可以工作。

这里是最简单的方法,不需要将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