




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 <stdio.h>
2#include <string.h>
3
4int maximum69Number(int num) {
5    char numStr[5];
6    sprintf(numStr, "%d", num); // Convert integer to string
7    for (int i = 0; numStr[i] != '\0'; ++i) {
8        if (numStr[i] == '6') {
9            numStr[i] = '9';
10            break;
11        }
12    }
13    return atoi(numStr); // Convert string back to integer
14}
15
16int main() {
17    int num = 9669;
18    printf("%d", maximum69Number(num));
19    return 0;
20}The function maximum69Number converts the given number to a string, checks each character, and replaces the first '6' with a '9'. Once done, it converts the string back to an integer and returns it.
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.
1using namespace std;
int maximum69Number (int num) {
    int mod = 10000;
    for (int i = 4; i >= 0; i--) {
        if ((num / mod) % 10 == 6) {
            num += 3 * mod;
            break;
        }
        mod /= 10;
    }
    return num;
}
int main() {
    int num = 9669;
    cout << maximum69Number(num);
    return 0;
}The C++ solution uses integer division to figure out the value of individual digits and alters the first '6' to '9' using arithmetic.