Feb-16-2019, 06:09 PM
Could anyone help me in the following problem from https://artofproblemsolving.com/communit...ts_ordered . Given a positive integer n, find the smallest positive integer m>n whose digits are in ascending or descending order. I tried to do recursively two functions where the first finds the next number whose digits are in ascending order and the seconds the next number whose digits are in descending order. But I am not sure how to do the recursion? It looks like the decreasing function does not work properly.
def increasing(n): asastring = str(n) length = len(asastring) if asastring == "9"*length: return "1"*(length+1) if length == 1: return int(n)+1 if length >= 2: firstcharacter = asastring[0] secondcharacter = asastring[1] if int(firstcharacter) > int(secondcharacter): return int(str(firstcharacter)*length) if firstcharacter == secondcharacter: return firstcharacter+str(increasing(int(asastring[1:]))) if int(firstcharacter) < int(secondcharacter): if secondcharacter == "9": return str(int(firstcharacter)+1) * len(str(n)) return firstcharacter+str(increasing(int(asastring[1:]))) def decreasing(n): asastring = str(n) length = len(asastring) if length > 1: if asastring == "1"+"0"*(len(asastring)-1): return "11"+"0"*(len(asastring)-2) if len(asastring) == 1: if asastring == 9: return 11 else: return int(n)+1 if len(asastring) >= 2: firstcharacter = asastring[0] secondcharacter = asastring[1] #print("f:"+str(asastring[0])+" s:"+str(asastring[1])) if int(firstcharacter) > int(secondcharacter): if int(secondcharacter) > 0: return str(str(firstcharacter)+str(int(secondcharacter)-1)) else: return str(str(int(firstcharacter) -1)*2) if firstcharacter == secondcharacter: return firstcharacter+str(decreasing(int(asastring[1:]))) if int(firstcharacter) < int(secondcharacter): if secondcharacter == "9": return str(int(firstcharacter)+1) * len(str(n)) return firstcharacter+str(decreasing(int(asastring[1:]))) i=1 for j in range(100): i = min(int(increasing(i)),int(decreasing(i))) print(i)