Leetcode 1323. Maximum 69 Number
You are given a positive integer. You can swap at most one digit of the number to get the maximum possible number. The number is composed of only the digits 6 and 9.
#include <iostream>
#include <string>
class Solution {
public:
int maximum69Number (int num) {
// Convert the number to a string for easy digit manipulation
std::string numStr = std::to_string(num);
// Traverse the string and change the first occurrence of '6' to '9'
for (char& c : numStr) {
if (c == '6') {
c = '9';
break; // Only change the first '6'
}
}
// Convert the modified string back to an integer
return std::stoi(numStr);
}
};
int main() {
Solution sol;
// Example test case
int num = 9669;
std::cout << "Original number: " << num << "\n";
std::cout << "Maximum possible number: " << sol.maximum69Number(num) << "\n";
return 0;
}
n
is the number of digits in the input number. This is because we’re iterating through each digit at most once.This approach ensures efficiency both in terms of time and space, considering the digit manipulation involved.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?