
Sponsored
Sponsored
This approach uses a simple greedy algorithm to find the first occurrence of the digit '6' and replaces it with '9'. This ensures that the number is maximized by making a change that increases the most significant portion of the number.
Time Complexity: O(n), where n is the number of digits in num.
Space Complexity: O(n) for storing the string representation of num.
1#include <iostream>
2#include <string>
3using namespace std;
4
5int maximum69Number(int num) {
6    string numStr = to_string(num);
7    for (char &c : numStr) {
8        if (c == '6') {
9            c = '9';
10            break;
11        }
12    }
13    return stoi(numStr);
14}
15
16int main() {
17    int num = 9669;
18    cout << maximum69Number(num);
19    return 0;
20}This C++ implementation converts the integer to a string to iterate over each digit, making a replacement at the first occurrence of '6'. It then converts the string back to an integer.
This approach works directly with the number without converting it to a string. We find the first '6' from the leftmost side by using basic mathematical operations (division and modulo). We can calculate the position and change the digit using arithmetic transformations to make this efficient.
Time Complexity: O(1), as we have at most 4 digits to check.
Space Complexity: O(1), using constant space for computations.
1
This Java code processes the digits of the number by directly calculating each decimal place. It shifts the first '6' found to '9' by adding 3 times the power of 10 matching the '6'.