简体   繁体   English

Python:获取最大的 n 位数

[英]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.

相关问题 最大回文集,是两个n位数字的乘积(Python) - Largest palindrome which is product of two n-digit numbers (Python) 在一个数字序列中找到最大的 n 位乘积 - Finding the largest n-digit product in a sequence of numbers 如何在Python中打印右对齐的货币符号和n位十进制数字 - How to print currency symbol and an n-digit decimal number right aligned in Python 如何形成给定数字的所有可能组合以形成不重复数字的n位数字?(python) - How to form all possible combination of given digits to form a n-digit number without repetition of digits?(python) 我们如何找到一个 n 位数字的排列? - How can we find the permutations of a n-digit number? 完整的 n 位因子 - Complete n-Digit Factor Python 3 - 递归查找具有和不具有唯一数字的 n 位代码 - Python 3 - Recursively finding n-digit code with and without unique digits 选择n组整数,以最大化满足任意条件的n位数排列的数量 - Choosing n sets of integers that maximize the number of n-digit number permutations that satisfy an arbitrary condition 编写一个输入正整数n并返回可除以17的n位正整数的数量的函数 - Write a function that input a positive integer n and return the number of n-digit positive integers that divisible by 17 打印所有 n 位数字,其数字的乘积等于给定的产品 python - Print all n-digit numbers whose product of digits equals to given product python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM