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 <stdio.h>
2#include <string.h>
3
4char* largestOddNumber(char *num) {
5 int length = strlen(num);
6 for (int i = length - 1; i >= 0; i--) {
7 if ((num[i] - '0') % 2 != 0) {
8 num[i + 1] = '\0';
9 return num;
10 }
11 }
12 return "";
13}
14
15int main() {
16 printf("%s\n", largestOddNumber("52"));
17 printf("%s\n", largestOddNumber("4206"));
18 printf("%s\n", largestOddNumber("35427"));
19 return 0;
20}
This function iterates from the end of the string, checking each digit to see if it is odd. Once it finds an odd digit, it marks the end of the string there and returns the substring from the start to that point.
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.
1import re
2
3def largestOddNumber(num:
This solution reverses the string and searches for the first occurrence of an odd digit using a regex pattern. Once found, it calculates the original position and slices the string accordingly.