###### tags: `Leetcode` `medium` `math` `python` # 670. Maximum Swap ## [題目連結:] https://leetcode.com/problems/maximum-swap/ ## 題目: You are given an integer ```num```. You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get. **Example 1:** ``` Input: num = 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. ``` **Example 2:** ``` Input: num = 9973 Output: 9973 Explanation: No swap. ``` ## 解題想法: * 要求可以任兩數交換位置一次(也可以不交換),使得num最大 * 暴力法:雙for迴圈,每個位置都交換,選出最大的 ## Python: ``` python= class Solution(object): def maximumSwap(self, num): """ :type num: int :rtype: int """ nums= list(str(num)) res=num for i in range(len(nums)-1): for j in range(i+1,len(nums)): nums[i],nums[j]=nums[j],nums[i] res=max(res,int("".join(val for val in nums))) nums[i],nums[j]=nums[j],nums[i] return res result=Solution() ans=result.maximumSwap(num = 2736) print(ans) ```