1
+ // Runtime: 28 ms (Top 84.21%) | Memory: 14.9 MB (Top 67.84%)
1
2
class Solution {
2
3
public:
3
4
string largestOddNumber (string num) {
4
5
// Length of the given string
5
- int len = num.size ();
6
+ int len = num.size ();
6
7
// We initialize an empty string for the result
7
- string res = " " ;
8
- // We start searching digits from the very right to left because we want to find the first odd digit
9
- // Which will be the last digit of our biggest odd number
8
+ string res = " " ;
9
+ // We start searching digits from the very right to left because we want to find the first odd digit
10
+ // Which will be the last digit of our biggest odd number
10
11
for (int i = len - 1 ; i >= 0 ; i--) {
11
- // Here we just convert char to an integer in C++
12
- // We can also do the reverse operation by adding '0' to an int to get char from an int
12
+ // Here we just convert char to an integer in C++
13
+ // We can also do the reverse operation by adding '0' to an int to get char from an int
13
14
int isOdd = num[i] - ' 0' ;
14
- // We check if the current digit is odd, if so this is the position we want to find
15
+ // We check if the current digit is odd, if so this is the position we want to find
15
16
if (isOdd % 2 == 1 ) {
16
- // Since we have found the correct spot, let's create our result string
17
- // We can basically extract the part starting from 0th index to right most odd digit's index
18
- // Like this:
19
- // 0123456 -> indices
20
- // 1246878 -> digits
21
- // ^....^ -> The part we extracted [0 to 5]
17
+ // Since we have found the correct spot, let's create our result string
18
+ // We can basically extract the part starting from 0th index to right most odd digit's index
19
+ // Like this:
20
+ // 0123456 -> indices
21
+ // 1246878 -> digits
22
+ // ^....^ -> The part we extracted [0 to 5]
22
23
res = num.substr (0 , i + 1 ); // i+1 is length of substring
23
- // Because we know this would be the largest substring as we are starting from last
24
- // We can terminate the loop and return the result
24
+ // Because we know this would be the largest substring as we are starting from last
25
+ // We can terminate the loop and return the result
25
26
break ;
26
27
}
27
28
}
28
29
return res;
29
30
}
30
- };
31
+ };
0 commit comments