For this question, I need to find the largest three-digit number within a larger number.
Sample Test Case 1:
534535
Output:
535
Sample Test Case 2 :
23457888976
Output :
976
#include <iostream>
using namespace std;
int main() {
int num;
cin>>num;
int len= to_string(num).length();
int arr[10],lnum=0,max=0;
for (int i =len-1;i>=0;i--)
{
arr[i] = num%10;
num =num/10; //to convert int into array
}
for (int i=0;i<len-2;i++)
{
if (arr[i] >arr[i+1])
lnum = arr[i]*100+arr[i+1]*10+arr[i];
if (lnum>max)
max= lnum;
}
cout<<max;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
int i, n;
string s;
cin >> s;
n = (int)s.size();
if(n<3){
/* there are less than 3 digits in the input number
Here, you can print the number itself as it will be largest number or
print -1 which can state that no 3 digit number exists.
*/
cout<<-1;
return 0;
}
int maxans = (s[0]-'0')*100 + (s[1]-'0')*10 + (s[2]-'0');
// storing the first 3 digits as the maximum answer till now.
int prev = maxans;
for(i = 3;i<n;i++){
int cur = (prev%100)*10 + (s[i]-'0'); // using %100 to extract the last two digits and then multiplying by 10 and adding the ith digit to make the next 3 digit number.
maxans = max(maxans, cur);
prev = cur;
}
cout<<maxans;
return 0;
}
This code is of time complexity O(n) where n is the length of input string and space complexity O(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With