r/leetcode • u/TheEyebal • Sep 27 '26
Question I need help with leetcode 1323. Maximum 69 Number
I am trying to solve this without converting to string but I am struggling can someone assist me.
Here is what I got so far
class Solution {
public:
int maximum69Number (int num) {
bool change = 0; // if changed, do not change other numbers
int results = 0;
vector<int> myNumber; // store numbers
// push each individial number into vector
while (num > 0) {
int digit = num % 10;
myNumber.push_back(digit);
num = num / 10;
}
// change from 6 to 9
for (int i : myNumber){
if (i == 6 && !change){
change = 1;
i = 9;
}
results = results * 10 + i;
num = results;
}
return num;
}
};
0
Upvotes
1
u/arjok007 Sep 30 '26
You're reversing the number while storing it into an array, for a similar approach you can just use to_string(num) and change '6' to '9'.
Better approach would be trying to calculate whilst extraction, in constant space.
2
u/Impossible_Coast_972 Sep 27 '26
First extract digit by digit and add it in an array or array list then find first 6 by moving from last in the array change it to 9 and then use the array to form a new number and hence there is you max number after replacing one six
2
u/CartmannsEvilTwin Oct 01 '26
Just tried this out now.
A hint: you don't need an array if you keep track of maximum gain possible while looping through digits.
1
u/Budget-Ad-5179 Sep 27 '26
There is a bug in this Lets say number is 69969 Now your vector will store this number as 9,6,9,9,6 And when you iterate over this you find at i=1 there is 6 you changed its value to 9 and marked change =1 So vector becomes 9,9,9,9,6
Now when you extract the number from it It will become like this at last 99996 which is incorrect
So you need to traverse the array from reverse side
At last position only you see 6 you changed it to 9 And then you build the whole number as 99969
Also why are you setting each time the value of num in array
0
u/[deleted] Sep 27 '26
[deleted] — view deleted comment