I'm trying to find an efficient method to count the number of positive integers less or equal than a certain number x that have at least one digit that repeating.
I tried to count the numbers that have repeating digits and then substract it from x, but my program became too slow for x up to 10^10.
I searched and I found two ways to implement this idea:
def count_unique(x):
cnt = 0
for i in range (x + 1):
num = i
visited = [0,0,0,0,0,0,0,0,0,0]
while (num):
if visited[num % 10] == 1:
break
visited[num % 10] = 1
num = (int)(num / 10)
if num == 0:
cnt += 1
return cnt -1
for i in range(int(input())):
x = int(input())
print(x - count_unique(x))
And :
Prefix = [0]
def repeated_digit(n):
a = []
while n != 0:
d = n%10
if d in a:
return 0
a.append(d)
n = n//10
return 1
def pre_calculation(MAX):
global Prefix
Prefix.append(repeated_digit(1))
for i in range(2,MAX+1):
Prefix.append(repeated_digit(i)+Prefix[i-1])
MAX = 10000000000
pre_calculation(MAX)
for i in range(int(input())):
x = int(input())
print(x - Prefix[x])
but unfortunately none of them was fast enough, Does anyone have a better way to achieve this?
Sample input:
2 #number of test cases
10
20
Sample Output : (the result for each test case)
0 #no number less than 10 with a repeating digit
1 #one number less than 20 with a repeating digit (which is 11)