Sponsored
If the entire string is considered as a whole number, you only need to check the last digit to determine if it's odd. This is because the entire substring from start to that odd digit will be the largest odd number available. If there is no odd digit, then there's no odd number in the string.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1) because only a constant amount of space is used.
1#include <iostream>
2#include <string>
3
4std::string largestOddNumber(std::string num) {
5 for (int i = num.size() - 1; i >= 0; --i) {
6 if ((num[i] - '0') % 2 != 0) {
7 return num.substr(0, i + 1);
8 }
9 }
10 return "";
11}
12
13int main() {
14 std::cout << largestOddNumber("52") << std::endl;
15 std::cout << largestOddNumber("4206") << std::endl;
16 std::cout << largestOddNumber("35427") << std::endl;
17 return 0;
18}
The function operates similarly to the C version, traversing from the end of the string back to the beginning, returning the longest substring that ends with an odd digit if any exist.
By utilizing regular expressions, find the largest substring ending in any odd digit directly. This will require reversing the string and searching for the first odd digit using a pattern.
Time Complexity: O(n), mainly due to the string reversal and regex search.
Space Complexity: O(n) for the reversed string.
1function largestOddNumber(num) {
2 const reversedNum =
JavaScript's approach uses regex to find the first odd digit after reversing the number. Then, it calculates the original index and slices the string from the start to that point.