[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 题目讲解汇总(持续更新中...)

posted @ 2022-12-04 07:44  Grandyang  阅读(125)  评论(0编辑  收藏  举报
Fork me on GitHub