繁体   English   中英

Python:获取最大的 n 位数

[英]Python: Getting largest n-digit number

非常愚蠢的问题,但我怎样才能用 python 快速获得最大的 n 位数? 很明显,数字总是出现 n 次 9。所以 n=1 -> 9,n=2 -> 99 等等。

我所拥有的是:

max_str = ''
# there should be a better way to do this, right?
for i in range(self.number_length):
    max_str += '9'
max_value = int(max_str)

这行得通。 但正如评论所说,一定有更好的方法,对吧?

编辑:

我对不同的选项进行了快速而肮脏的性能比较:

%%timeit
10**5 - 1
8.97 ns ± 0.0952 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
%%timeit
pow(10,5)-1
305 ns ± 1.13 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit
int("9" * 5)
137 ns ± 0.321 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%%timeit
max_str = ''
for i in range(5):
    max_str += '9'
401 ns ± 1.63 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

10**n - 1 出于某种原因是迄今为止最快的解决方案,而 pow(10,n) -1 并不比我的循环方法快多少。

您需要做的就是:

10**n - 1

其中n是所需的位数。

n_largest_number=pow(10,n)-1

解释: pow(a,b) function 输出 a^b。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM