1. 程式人生 > 其它 >[LeetCode] 1323. Maximum 69 Number 6和9組成的最大數字

[LeetCode] 1323. Maximum 69 Number 6和9組成的最大數字


You are given a positive integer num consisting only of digits 6 and 9.

Return the maximum number you can get by changing at most one digit (6* becomes 9, and 9 becomes 6)*.

Example 1:

Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.

Example 2:

Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.

Example 3:

Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.

Constraints:

  • 1 <= num <= 104
  • num consists of only 6 and 9 digits.

這道題說是給了一個只含有6和9的正整數,現在說是可以將6變成9,或者將9變成6,最多可以變換一次,讓返回可以得到的最大的數字。既然要得到最大的數字,那麼肯定是把6變成9得到的數字最大,而且儘量去變高位上的數字。所以方法就是從高位開始遍歷,若遇到6,則變為9即可,變換了之後直接 break 掉就行了,因為最多隻能變換一次。為了能方便從高位開始遍歷,可以將給定的數字轉為字串開始遍歷,之後變換完了之後再轉為整型數就可以了,參見程式碼如下:


class Solution {
public:
    int maximum69Number (int num) {
        string str = to_string(num);
        for (char &c : str) {
            if (c == '6') {
                c = '9';
                break;
            }
        }
        return stoi(str);
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1231


參考資料:

https://leetcode.com/problems/maximum-69-number/

https://leetcode.com/problems/maximum-69-number/solutions/2640037/maximum-69-number/

https://leetcode.com/problems/maximum-69-number/solutions/484292/java-python-replace-once/


LeetCode All in One 題目講解彙總(持續更新中...)