Finding the largest three-dgit number "within" a number

  c++

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


I’ve tried the following code:

        #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;
    }

Although this code seems to work for Test Case 1, it doesn’t work for most of the inputs.


(Please do help with this too. )
1. This is for numbers with 10-digits only (that too, most of it have wrong output). What to do in case of bigger numbers?
2. Is there any better way to convert the integer into an array? Or will a string array work in similar way?
3. It’s really slow, can anyone help me figure out how to speed this up?


Thanks for any help !!
Source: Windows Questions C++

LEAVE A COMMENT