常规解法,略显冗余
class Solution {
public:
int maximum69Number (int num) {
stack<int> stack;
int nums = 0,changed = 0;
while(num)
{
stack.push(num % 10);
num /= 10;
}
while(!stack.empty())
{
if(stack.top() == 6 && !changed && (changed = 1))
nums = nums * 10 + 9;
else
nums = nums * 10 + stack.top();
stack.pop();
}
return nums;
}
};
运行结果:
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Maximum 69 Number.
Memory Usage: 6.3 MB, less than 5.08% of C++ online submissions for Maximum 69 Number.
直接转成字符串,然后替换第一个6,再转回数字:
class Solution {
public:
int maximum69Number (int num) {
string s = to_string(num);
for(auto &c:s)
{
if(c =='6'){c='9';break;}
}
return stoi(s);
}
};