Find the largest odd number in String
Last Updated :
14 Aug, 2023
Given a string S, representing a large integer, the task is to return the largest-valued odd integer (as a string) that is a substring of the given string S.
Note: A substring is a contiguous sequence of characters within a string. A null string (“”) is also a substring.
Examples:
Input: S = “504”
Output: “5”
Explanation: The only substring “5” is an odd number.
Input: S = “2042”
Output: “”
Explanation: All the possible non-empty substrings have even values.
Approach: To solve the problem follow the below idea:
The idea is to check odd number from the last in the string just to return the largest odd number.
Follow the steps to solve the problem:
- Iterate through i = s.length – 1 till 0:
- Check if s[i] is odd then return the substring from 0 to i+1.
- Return an empty string in case of no odd number.
Below is the implementation for the above approach:
C++
#include <iostream>
using namespace std;
string maxOdd(string s)
{
for ( int i = s.length() - 1; i >= 0; i--) {
if (s[i] % 2 != 0) {
string s1 = s.substr(0, i + 1);
return s1;
}
}
return "" ;
}
int main()
{
string s = "504" ;
string ans = maxOdd(s);
cout << ans;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static String maxOdd(String s)
{
for ( int i = s.length() - 1 ; i >= 0 ; i--)
{
if (s.charAt(i) % 2 != 0 )
{
String s1 = s.substring( 0 , i + 1 );
return s1;
}
}
return "" ;
}
public static void main(String[] args)
{
String s = "504" ;
String ans = maxOdd(s);
System.out.println(ans);
}
}
|
Python
def max_odd(s):
for i in range ( len (s) - 1 , - 1 , - 1 ):
if int (s[i]) % 2 ! = 0 :
return s[:i + 1 ]
return ""
s = "504"
ans = max_odd(s)
print (ans)
|
C#
using System;
class GFG {
public static string maxOdd( string s)
{
for ( int i = s.Length - 1; i >= 0; i--)
{
if (s[i] % 2 != 0)
{
string s1 = s.Substring(0, i + 1);
return s1;
}
}
return "" ;
}
public static void Main()
{
string s = "504" ;
string ans = maxOdd(s);
Console.WriteLine(ans);
}
}
|
Javascript
function maxOdd(s) {
for (let i = s.length - 1; i >= 0; i--) {
if (parseInt(s.charAt(i)) % 2 !== 0) {
return s.substring(0, i + 1);
}
}
return '' ;
}
const s = '504' ;
const ans = maxOdd(s);
console.log(ans);
|
Time Complexity: O(|S|).
Auxiliary Space: O(1).
Share your thoughts in the comments
Please Login to comment...