题目
给出一个非负整数,最多交换一次两个数字,找出能发现的最大整数。如果不存在,返回原数。如:
Example 1:
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973
Output: 9973
Explanation: No swap.
Python题解
class Solution(object):
def maximumSwap(self, num):
"""
:type num: int
:rtype: int
"""
nums = list(str(num))
ans = nums[:]
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
nums[i], nums[j] = nums[j], nums[i]
if ans < nums:
ans = nums[:]
nums[i], nums[j] = nums[j], nums[i]
return int(''.join(ans))