algoadvance

Leetcode 1323. Maximum 69 Number

Problem Statement

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).

Clarifying Questions

  1. What constraints are there on the size of the number?
    • The number will be a positive integer composed only of digits 6 and 9. The constraints on the number’s length are not specified in the problem, but usually leetcode problems adhere to typical integer ranges in Java.
  2. Can the number have more than one occurrence of digit 6 or 9?
    • Yes, the number can have multiple occurrences of 6 and 9.
  3. Do we only make one change or can we choose not to make any changes if it’s already maximized?
    • We are allowed to make one change at most. If it’s already maximized, we may choose not to make any changes.

Strategy

  1. Convert the number to a string: This makes it easier to iterate through the digits.
  2. Identify the first occurrence of digit ‘6’: Changing this to ‘9’ will give us the maximum number.
  3. Change the first ‘6’ to ‘9’: Convert the modified string back to an integer.
  4. Return the modified number.

Code

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
    }
}

Time Complexity

Space Complexity

This solution ensures that we only make the necessary one change to maximize the number efficiently.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI