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).
1 <= num <= 10^4num consists only of digits 6 and 9Use a greedy strategy to maximize the number by changing the first ‘6’ to ‘9’ from the left (most significant digit).
Algorithm:
This approach works because:
Alternative approaches include:
Example 1: num = 9669
Step-by-step execution:
Example 2: num = 9996
Step-by-step execution:
Example 3: num = 9999
Step-by-step execution:
Example 4: num = 6
Step-by-step execution:
class Solution {
public int maximum69Number(int num) {
char[] digits = String.valueOf(num).toCharArray();
for (int i = 0; i < digits.length; i++) {
if (digits[i] == '6') {
digits[i] = '9';
break;
}
}
return Integer.parseInt(String.valueOf(digits));
}
}
class Solution {
public int maximum69Number(int num) {
// Find the largest power of 10 that divides num when it's all 9s
int temp = num;
int pos = 1;
// Find the position from right where we should change 6 to 9
while (temp >= 10) {
pos *= 10;
temp /= 10;
}
// Start from leftmost digit
temp = num;
while (pos > 0) {
int digit = temp / pos;
if (digit == 6) {
return num + 3 * pos; // 6 -> 9 increases by 3 * 10^pos
}
temp %= pos;
pos /= 10;
}
return num;
}
}
Explanation: Use mathematical operations to find and modify the leftmost ‘6’ without string conversion.
Time Complexity: O(n) - where n is number of digits Space Complexity: O(1) - constant space
class Solution {
public int maximum69Number(int num) {
return Integer.parseInt(String.valueOf(num).replaceFirst("6", "9"));
}
}
Explanation: Use String’s replaceFirst method to replace the first occurrence of ‘6’ with ‘9’.
Time Complexity: O(n) - string operations Space Complexity: O(n) - for string creation