Largest Odd Number in String LeetCode solution in C++

1
class Solution {
2
public:
3
string largestOddNumber(string num) {
4
// Length of the given string
5
int len = num.size();
6
// 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
9
// find the first odd digit Which will be the last digit of our biggest odd
10
// number
11
for (int i = len - 1; i >= 0; i--) {
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
14
// char from an int
15
int isOdd = num[i] - '0';
16
// We check if the current digit is odd, if so this is the position we
17
// want to find
18
if (isOdd % 2 == 1) {
19
// Since we have found the correct spot, let's create our result string
20
// We can basically extract the part starting from 0th index to right
21
// most odd digit's index Like this: 0123456 -> indices 1246878 ->
22
// digits
23
// ^....^ -> The part we extracted [0 to 5]
24
res = num.substr(0, i + 1); // i+1 is length of substring
25
// Because we know this would be the largest substring as we are
26
// starting from last We can terminate the loop and return the result
27
break;
28
}
29
}
30
return res;
31
}
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0