Find largest valued even integer which is a non-empty substring of S
Last Updated :
31 Jan, 2022
Given a string S of size N, representing a large integer. The task is to find the largest valued even integer which is a non-empty substring of S. If no even integer can be made then return an empty string.
Examples:
Input: S = “4206”
Output: “4206”
Explanation: “4206” is already an even number.
Input: S = “23”
Output: “2”
Explanation: “The only non-empty substrings are “2”, “3”, and “23”. “2” is the only even number.
Input: S = “17”
Output: “”
Explanation: There is no even valued substring in the given string
Approach: The task can be solved by finding the first even character from the right, let’s say, it is found at an index ‘idx‘.
The resultant largest even valued non-empty substring would be the substring of S in the range [0, idx].
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void get(string& s)
{
int N = s.length();
int idx = -1;
for ( int i = N - 1; i >= 0; i--) {
if ((s[i] - '0' ) % 2 == 0) {
idx = i;
break ;
}
}
if (idx == -1)
cout << "" ;
else
cout << s.substr(0, idx + 1);
}
int main()
{
string S = "4206" ;
get(S);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static void get(String s)
{
int N = s.length();
int idx = - 1 ;
for ( int i = N - 1 ; i >= 0 ; i--) {
if ((s.charAt(i) - '0' ) % 2 == 0 ) {
idx = i;
break ;
}
}
if (idx == - 1 )
System.out.print( "" );
else
System.out.print(s.substring( 0 , idx + 1 ));
}
public static void main (String[] args) {
String S = "4206" ;
get(S);
}
}
|
Python3
def get(s):
N = len (s);
idx = - 1 ;
for i in range (N - 1 , 0 , - 1 ):
if (( ord (s[i]) - ord ( '0' )) % 2 = = 0 ):
idx = i;
break ;
if (idx = = - 1 ):
print ("");
else :
print (s[ 0 : idx + 1 ]);
S = "4206" ;
get(S);
|
C#
using System;
class GFG {
static void get ( string s)
{
int N = s.Length;
int idx = -1;
for ( int i = N - 1; i >= 0; i--) {
if ((s[i] - '0' ) % 2 == 0) {
idx = i;
break ;
}
}
if (idx == -1)
Console.Write( "" );
else
Console.Write(s.Substring(0, idx + 1));
}
public static void Main () {
string S = "4206" ;
get (S);
}
}
|
Javascript
<script>
function get(s)
{
let N = s.length;
let idx = -1;
for (let i = N - 1; i >= 0; i--)
{
if ((s[i].charCodeAt(0) - '0' .charCodeAt(0)) % 2 == 0)
{
idx = i;
break ;
}
}
if (idx == -1)
document.write( "" );
else
document.write(s.slice(0, idx + 1));
}
let S = "4206" ;
get(S);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...