Example of what I am looking for:
Input: M = 5, K = 3
Output: 23
Sequence of numbers starting from 1 with digit sum as 5 is as follows:
5
14
23
32
41
So 3rd smallest number is 23
My approach, it gives me what I am looking for, but I don't think this is the optimal way to do it. A lot of unnecessary calculations are taking place when K>1. In my solution, I am referring M as num and K as position.
def kthsmallest(num, position):
pos=1
#return first or you can say minimum number whose sum of digits is equal to num when k=1 or 0
if position == 0:
return 0
if position ==1:
return str(num % 9) + ('9' * (num//9))
#when given kth position is more than 1
if position >1:
i =num
while True:
#Inilitize sum =0 and on each iteration it will set 0
sum = 0
#Calculate sum of digits in number i
for digit in str(i):
sum = sum+ int(digit)
#Check if sum of digits is equal to number given
if sum ==num:
if pos == position:
return i
pos +=1
i +=1
print(kthsmallest(21,2))
Can somebody help me to refactor the code? or can suggest a completely new approach to do it. Please comment if more info required.