1323. Maximum number 69 – Leetcode Explanation

I hope you have read the problem. Here is the solution of Leetcode 1323. Maximum number 69 :
So in the problem we are given a positive integer consisting of only digits 6 and 9 , and we have to make the number as large as possible by chaning at most one digit.
Note that we should always try to maximize the largest digit , i.e the digit to the left to get greater values , i.e; a tenth’s place should be given more priority than a unit’s place and so on. So , we can change the leftmost 6 (if there exists any) to 9 to get the largest number. We can do it using to_string and stoi ( string to integer) function in c++

Here is the code :

class Solution {
public:
    int maximum69Number (int num) {
        string x = to_string(num);
        for(int i = 0 ; i < (int)x.size() ; i++) {
            if(x[i] == '6') {
                x[i] = '9';
                break;
            }
        }
        int ans = stoi(x);
        return ans;
    }
};

Leave a Comment