[英]Python: Getting largest n-digit number
Very stupid question but how can I quickly get the largest n-digit number with python?非常愚蠢的问题,但我怎样才能用 python 快速获得最大的 n 位数? It's clear that number will always be n-occurrences of 9. So n=1 -> 9, n=2 -> 99 etc.
很明显,数字总是出现 n 次 9。所以 n=1 -> 9,n=2 -> 99 等等。
What I have is this:我所拥有的是:
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)
This works.这行得通。 But as the comment says, there must be a better way, right?
但正如评论所说,一定有更好的方法,对吧?
EDIT:编辑:
I made a quick and dirty performance comparison of the different options:我对不同的选项进行了快速而肮脏的性能比较:
%%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 for some reason is by far the fastest solution while pow(10,n) -1 isn't much faster than my loop approach. 10**n - 1 出于某种原因是迄今为止最快的解决方案,而 pow(10,n) -1 并不比我的循环方法快多少。
All you need to do is:您需要做的就是:
10**n - 1
where n
is the desired number of digits.其中
n
是所需的位数。
n_largest_number=pow(10,n)-1
Explanation: pow(a,b) function outputs a^b.解释: pow(a,b) function 输出 a^b。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.