Created
February 5, 2025 14:25
-
-
Save MahraibFatima/8e64739a7d7532e12a439c59c361e4c8 to your computer and use it in GitHub Desktop.
Largest Odd Number in String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
using namespace std; | |
// Brute Force | |
string largestOddNumber(string number) { | |
int save = -1; | |
for(int i=number.size()-1; i>=0; --i){ | |
// string ch = ; | |
int n = number[i] - '0'; | |
// cout<<n<<endl; | |
if(n%2 != 0) {// odd | |
save = i; | |
break; | |
} | |
} | |
string odd_number=""; | |
if(save != -1){ | |
for(int i=0; i<save+1; ++i) | |
odd_number += number[i]; | |
} | |
return odd_number; | |
} | |
//Optimized one | |
// string largestOddNumber(string num) { | |
// int n = num.size(); | |
// for(int i = n-1; i >= 0; i--){ | |
// if((num[i] - '0') % 2 != 0 ){ | |
// return num.substr(0, i+1); | |
// } | |
// } | |
// return ""; | |
// } | |
int main(){ | |
string number = "240"; | |
cout<< largestOddNumber(number); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment