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.
1using System;
2
3public class LargestOddNumber {
4 public static string largestOddNumber(string num) {
5 for (int i = num.Length - 1; i >= 0; i--) {
6 if ((num[i] - '0') % 2 != 0) {
7 return num.Substring(0, i + 1);
8 }
9 }
10 return "";
11 }
12
13 public static void Main() {
14 Console.WriteLine(largestOddNumber("52"));
15 Console.WriteLine(largestOddNumber("4206"));
16 Console.WriteLine(largestOddNumber("35427"));
17 }
18}
The C# solution functions by scanning from end to start, yielding the longest substring ending with an odd digit.
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.