[LeetCode] 1323. Maximum 69 Number

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 组成的正整数 num。

你最多只能翻转一位数字,将 6 变成 9,或者把 9 变成 6 。

请返回你可以得到的最大数字。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-69-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题不难,就是字符串和数字的转换,我直接上代码,看了就能懂。

时间O(n)

空间O(n) - StringBuilder

Java实现

 1 class Solution {
 2     public int maximum69Number (int num) {
 3         String str = String.valueOf(num);
 4         StringBuilder sb = new StringBuilder();
 5         boolean change = false;
 6         for (char c : str.toCharArray()) {
 7             if (c != '9' && change == false) {
 8                 c = '9';
 9                 change = true;
10             }
11             sb.append(c);
12         }
13         return Integer.parseInt(sb.toString());
14     }
15 }

 

LeetCode 题目总结

posted @ 2022-11-08 00:33  CNoodle  阅读(94)  评论(0)    收藏  举报