Similar Problems

Similar Problems not available

Maximum 69 Number - Leetcode Solution

Companies:

LeetCode:  Maximum 69 Number Leetcode Solution

Difficulty: Easy

Topics: greedy math  

Problem Description:

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

Example:

Input: num = 9669

Output: 9969

Explanation: Changing the first digit results in 6669.

Changing the second digit results in 9969.

Changing the third digit results in 9699.

Changing the fourth digit results in 9666.

Hence the maximum number is 9969.

Solution:

The problem is quite simple, as we just need to change the first occurrence of the digit 6 to 9.

We can loop through the digits of the input number and check if the current digit is 6. If it is, then we change it to 9 and break out of the loop as we only need to change one digit.

In code, this looks like the following:

class Solution {
public:
    int maximum69Number (int num) {
        string s = to_string(num);  // convert integer to string
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '6') {
                s[i] = '9';  // change the first 6 to 9
                break;
            }
        }
        return stoi(s);  // convert string to integer and return
    }
};

We first convert the integer num to a string s using the to_string function. Then we loop through the characters of s using a for loop and check if the current character is equal to the character '6'. If it is, we change it to '9', breaking out of the loop.

Finally, we convert the string s back to an integer using the stoi function and return the result.

Overall, the time complexity of this solution is O(n) where n is the number of digits in the input number. The space complexity is also O(n) as we are converting the integer to a string.

Maximum 69 Number Solution Code

1