海绵宝宝撒
不转换为字符串import mathdigits = int(math.log10(n))+1同时处理零和负数import mathif n > 0: digits = int(math.log10(n))+1elif n == 0: digits = 1else: digits = int(math.log10(-n))+2 # +1 if you don't count the '-' 您可能希望将其放入函数中:)这是一些基准。在len(str())已经落后的甚至是相当小的数字timeit math.log10(2**8)1000000 loops, best of 3: 746 ns per looptimeit len(str(2**8))1000000 loops, best of 3: 1.1 µs per looptimeit math.log10(2**100)1000000 loops, best of 3: 775 ns per loop timeit len(str(2**100))100000 loops, best of 3: 3.2 µs per looptimeit math.log10(2**10000)1000000 loops, best of 3: 844 ns per looptimeit len(str(2**10000))100 loops, best of 3: 10.3 ms per loop