Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int nextGreaterElement(int n) {
- int temp=n;
- int count=0;
- while(temp)
- {
- temp/=10;
- count++;
- }
- temp=n;
- vector<int> v(count);
- for(int i=count-1;i>=0;i--)
- { v[i]+=temp%10;
- temp/=10;
- }
- unsigned int ans=0;
- int j,k;
- int flag=0;
- for(int i=count-2;i>=0;i--){
- if(v[i+1]-v[i]>0){
- j=i;
- flag=1;
- break;
- }
- }
- if(flag==1)
- {
- for(int i=count-1;i>j;i--)
- {
- if(v[j]<v[i])
- {
- k=i;
- break;
- }
- }
- int temp =v[j];
- v[j]=v[k];
- v[k]=temp;
- for(int i=0;i<=j;i++)
- {
- ans=ans*10+(v[i]);
- }
- for(int i=count-1;i>j;i--)
- {
- ans=ans*10+(v[i]);
- }
- return ans;
- }
- else
- {
- return -1;
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement