我们认为一个数是好数,当且仅当它的十进制位数上,全部数位的数字都想同。给定一个正整数n,请问1-n中有多少好数。 示例: 输入 20 输出 10 说明 符合条件的有 1 2 3…
- User
我们认为一个数是好数,当且仅当它的十进制位数上,全部数位的数字都想同。给定一个正整数n,请问1-n中有多少好数。 示例: 输入 20 输出 10 说明 符合条件的有 1 2 3 4 5 6 7 8 9 11。
给出python代码,要求时间复杂度尽可能低。
- Assistant
To solve this problem efficiently, we can generate all numbers where all digits are the same and count those that are less than or equal to
n.Here is the Python code:
def count_good_numbers(n): count = 0 for k in range(1, 19): # Maximum length of n in digits (since n can be up to 10^18) for d in range(1, 10): # Digits from 1 to 9 number = int(str(d) * k) if number <= n: count += 1 else: # Since numbers with more digits will be larger, we can break early break return count # Example usage: n = int(input()) print(count_good_numbers(n))This code works by iterating over all possible lengths (
kfrom 1 up to 18, since the maximum number of digits innis 18 for 64-bit integers) and digits (dfrom 1 to 9). It constructs numbers by repeating the digitdktimes and checks if the number is less than or equal ton. If it is, it increments the count. If the constructed number exceeds , we can break early from the inner loop since any numbers with the same but higher will also exceed .