Leetcode 1323. Maximum 69 Number
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).
public class Maximum69Number {
public static int maximum69Number(int num) {
// Convert the number to a string to manipulate the digits more easily
String numStr = String.valueOf(num);
// Convert the string to a char array for in-place modification
char[] numArray = numStr.toCharArray();
// Iterate over the array and change the first '6' to '9'
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == '6') {
numArray[i] = '9';
break; // Only change the first '6'
}
}
// Convert the modified char array back to a string and then to an integer
return Integer.parseInt(new String(numArray));
}
public static void main(String[] args) {
int num = 9669;
System.out.println(maximum69Number(num)); // Output: 9969
num = 9999;
System.out.println(maximum69Number(num)); // Output: 9999
num = 669;
System.out.println(maximum69Number(num)); // Output: 969
}
}
n
is the number of digits in the number. This is because we are potentially iterating through all the digits of the number until we find the first ‘6’.This solution ensures that we only make the necessary one change to maximize the number efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?