
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
The Java solution leverages toString to convert the number into a character array for traversal, where it changes the first '6' to '9'. After the loop finishes, the new string representation is parsed 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#include <stdio.h>
2#include <math.h>
3
4int maximum69Number (int num) {
5    int mod = 10000;
6    for (int i = 4; i >= 0; i--) {
7        if ((num / mod) % 10 == 6) {
8            num += 3 * mod;
9            break;
10        }
11        mod /= 10;
12    }
13    return num;
14}
15
16int main() {
17    int num = 9669;
18    printf("%d", maximum69Number(num));
19    return 0;
20}This solution considers each digit by dividing the number with powers of 10. If a '6' is detected at a position, 3 times that power of 10 is added to change the digit to '9'.
Solve with full IDE support and test cases