1432. 改變一個整數能得到的最大差值
題目鏈接:1432. 改變一個整數能得到的最大差值
代碼如下:
class Solution {
public:int maxDiff(int num) {string s = to_string(num);function<int(char, char)> replace_stoi = [&](char old_char, char new_char)->int {int x = 0;for (char d : s) {char c = d == old_char ? new_char : d;x = x * 10 + (c - '0');}return x;};int mx = num;for (char d : s) {if (d != '9') {mx = replace_stoi(d, '9');break;}}int mn = num;if (s[0] != '1') {mn = replace_stoi(s[0], '1');}else {for (int i = 1;i < s.size();i++) {if (s[i] > '1') {//不是0也不是1mn = replace_stoi(s[i], '0');break;}}}return mx - mn;}
};