Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
Example 1:
Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973 Output: 9973 Explanation: No swap.
Note:
- The given number is in the range [0, 108]
class Solution {
public:
int maximumSwap(int num) {
int maxid = -1;
int maxdigit = -1;
int leftidx = -1;
int rightidx = -1;
string number = std::to_string(num);
for(int i=number.size()-1; i>=0; i--)
{
if(number[i] > maxdigit)
{
maxid = i;
maxdigit = number[i];
continue;
}
if(number[i] < maxdigit)
{
leftidx = i;
rightidx = maxid;
}
}
if(leftidx == -1) return num;
std::swap(number[leftidx], number[rightidx]);
return std::stoi(number);
}
};
python:class Solution(object):
def maximumSwap(self, num):
"""
:type num: int
:rtype: int
"""
number=str(num)
length=len(number)
maxid=-1
maxNumber=-1
leftid=-1
rightid=-1
for i in range(length-1,-1,-1):
if number[i] > maxNumber :
maxid = i
maxNumber = number[i]
continue
if number[i] < maxNumber :
leftid = i
rightid = maxid
if leftid == -1 : return num
list_number = list(number)
tmp = list_number[leftid]
list_number[leftid] = list_number[rightid]
list_number[rightid] = tmp
str_number = ''.join(list_number)
return int(str_number)