# 1432. Max Difference You Can Get From Changing an Integer¶

• Time: $O(\log \texttt{num})$
• Space: $O(\log \texttt{num})$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { public: int maxDiff(int num) { const string s = to_string(num); int firstNot9 = s.find_first_not_of('9'); int firstNot01 = s.find_first_not_of("01"); if (firstNot9 == string::npos) firstNot9 = 0; if (firstNot01 == string::npos) firstNot01 = 0; string a = s; string b = s; replace(a.begin(), a.end(), s[firstNot9], '9'); replace(b.begin(), b.end(), s[firstNot01], firstNot01 == 0 ? '1' : '0'); return stoi(a) - stoi(b); } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution { public int maxDiff(int num) { final String s = String.valueOf(num); final int firstNot9 = firstNot(s, '9', '9'); final int firstNot01 = firstNot(s, '0', '1'); final String a = s.replace(s.charAt(firstNot9), '9'); final String b = s.replace(s.charAt(firstNot01), firstNot01 == 0 ? '1' : '0'); return Integer.parseInt(a) - Integer.parseInt(b); } private int firstNot(final String s, char a, char b) { for (int i = 0; i < s.length(); ++i) if (s.charAt(i) != a && s.charAt(i) != b) return i; return 0; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution: def maxDiff(self, num: int) -> int: s = str(num) def firstNot(s: str, t: str) -> int: for i, c in enumerate(s): if all(c != d for d in t): return i return 0 firstNot9 = firstNot(s, '9') firstNot01 = firstNot(s, '01') a = s.replace(s[firstNot9], '9') b = s.replace(s[firstNot01], '1' if firstNot01 == 0 else '0') return int(a) - int(b)