Skip to content

Latest commit

 

History

History
139 lines (115 loc) · 2.81 KB

File metadata and controls

139 lines (115 loc) · 2.81 KB

中文文档

Description

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.

 

Constraints:

  • 0 <= num <= 108

Solutions

Python3

class Solution:
    def maximumSwap(self, num: int) -> int:
        chars = list(str(num))
        n = len(chars)
        for i in range(n - 1):
            mx = i + 1
            for j in range(i + 1, n):
                if ord(chars[j]) >= ord(chars[mx]):
                    mx = j
            if ord(chars[i]) < ord(chars[mx]):
                chars[i], chars[mx] = chars[mx], chars[i]
                break
        return int(''.join(chars))

Java

class Solution {
    public int maximumSwap(int num) {
        char[] chars = String.valueOf(num).toCharArray();
        int n = chars.length;
        for (int i = 0; i < n - 1; ++i) {
            int mx = i + 1;
            for (int j = i + 1; j < n; ++j) {
                if (chars[j] >= chars[mx]) {
                    mx = j;
                }
            }
            if (chars[i] < chars[mx]) {
                char t = chars[i];
                chars[i] = chars[mx];
                chars[mx] = t;
                break;
            }
        }
        return Integer.parseInt(String.valueOf(chars));
    }
}

C++

class Solution {
public:
    int maximumSwap(int num) {
        string s = to_string(num);
        int n = s.size();
        for (int i = 0; i < n - 1; ++i)
        {
            int mx = i + 1;
            for (int j = i + 1; j < n; ++j)
            {
                if (s[j] >= s[mx]) mx = j;
            }
            if (s[i] < s[mx])
            {
                swap(s[i], s[mx]);
                break;
            }
        }
        return stoi(s);
    }
};

Go

func maximumSwap(num int) int {
	s := strconv.Itoa(num)
	chars := []byte(s)
	n := len(chars)
	for i := range chars[:n-1] {
		mx := i + 1
		for j := i + 1; j < n; j++ {
			if chars[j] >= chars[mx] {
				mx = j
			}
		}
		if chars[i] < chars[mx] {
			chars[i], chars[mx] = chars[mx], chars[i]
			break
		}
	}
	ans, _ := strconv.Atoi(string(chars))
	return ans
}

...