Python easy to understand


  • 0
    P
    1. find the potential largest number NUM (76990 -> 99760 )
    2. compare NUM with num: find the first position that doesn't match (7 & 9 at index 0)
    3. Swap them (choose last 9 to make it maximum)
    class Solution(object):
        def maximumSwap(self, num):
            """
            :type num: int
            :rtype: int
            """
            numsstr = list(str(num))
            for i, x in enumerate(sorted(numsstr, reverse=True)):
            	if x > numsstr[i]:
            		pre, numsstr[i] = numsstr[i], x
            		break
            else:
            	return num
            for i in range(len(numsstr)):
            	if numsstr[~i] == x:
            		numsstr[~i] = pre
            		break
            return eval("".join(numsstr))
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.