algoadvance

Leetcode 1323. Maximum 69 Number

Problem Statement:

You are given a positive integer. You can swap at most one digit of the number to get the maximum possible number. The number is composed of only the digits 6 and 9.

Clarifying Questions:

  1. Input Constraints:
    • Should I expect to handle only positive integers?
    • Is the input guaranteed to contain only the digits 6 and 9?
  2. Output Clarification:
    • Should the function return the maximum number as an integer?
  3. Range Clarification:
    • What is the maximum range of the integer value we anticipate (to consider potential performance issues)?

Code:

#include <iostream>
#include <string>

class Solution {
public:
    int maximum69Number (int num) {
        // Convert the number to a string for easy digit manipulation
        std::string numStr = std::to_string(num);
        
        // Traverse the string and change the first occurrence of '6' to '9'
        for (char& c : numStr) {
            if (c == '6') {
                c = '9';
                break; // Only change the first '6'
            }
        }
        
        // Convert the modified string back to an integer
        return std::stoi(numStr);
    }
};

int main() {
    Solution sol;
    
    // Example test case
    int num = 9669;
    std::cout << "Original number: " << num << "\n";
    std::cout << "Maximum possible number: " << sol.maximum69Number(num) << "\n";
    
    return 0;
}

Strategy:

  1. Convert the Number to a String:
    • Convert the integer to a string format so that we can easily access and manipulate individual digits.
  2. Find the First ‘6’:
    • Traverse through the string and modify the first occurrence of the digit ‘6’ to ‘9’. This ensures that we are getting the maximum possible number by making the most significant change first.
  3. Convert Back to Integer:
    • After modifying the string, convert it back to an integer and return the result.

Time Complexity:

This approach ensures efficiency both in terms of time and space, considering the digit manipulation involved.

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