Problem
1903
Code
class Solution {
public:
bool isOdd(char c) { return ((c - '0') % 2); }
string largestOddNumber(string num) {
if (isOdd(num[num.size() - 1])) {
return num;
}
for (int i = num.size() - 2; i >= 0; i--) {
if (isOdd(num[i])) {
return num.substr(0, i + 1);
}
}
return "";
}
};
Logic
- A numeric character's value can be obtained by subtracting the
'0' character from it.
- By doing modulo 2, we can find out if it's even or odd.
- If odd, then remainder is 1 else its 0, automatically converted to a boolean value.
- Can omit the first if statement if we take the
num.size() - 1 but why go the extra step to call a loop?
string.substr(starting_index, up_until_index + 1) where the extra one is to include the up_until_index as well.