1323. Maximum 69 Number
1323. Maximum 69 Number
Easy
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.
Constraints:
1 <= num <= 10^4
num
's digits are 6 or 9.-
class Solution { public: int maximum69Number (int num) { string s_num=to_string(num); //C++中to_string函数将整数转为字符串 for(auto &ch:s_num){ if(ch=='6'){ ch='9'; break; } } return stoi(s_num); //stoi函数将字符串转换程整数 } };
class Solution: def maximum69Number (self, num: int) -> int: return str(num).replace('6','9',1)
Python中str(x)将x转化成string类型,string类中replace(old,new,[count])方法,将new字符串代替old字符串,count若省略,则所有old字符串都会被new代替