Task: Given a number N, Find the smallest number with same digits of n and that greater than n.
Example:
Input:
1
143
Output:
314
Here is the Code:
Program in C++:
- #include<iostream>
- #include<bits/stdc++.h>
- using namespace std;
- string nextGreaterNumber(string s)
- {
- for(int i=1;i<s.length();i++)
- {
- if(s[i-1]>=s[i])
- {
- if(i+1==s.length()) return "not possible";
- }
- else
- {
- break;
- }
- }
- stack<int> st;
- for(int i=s.length()-1;i>=0;i--)
- {
- if(s[i-1]>=s[i])
- {
- st.push(i);
- }
- else
- {
- st.push(i);
- int t;
- while(!st.empty()&&s[i-1]<s[st.top()])
- {
- t=st.top();
- st.pop();
- }
- swap(s[i-1],s[t]);
- reverse(s.begin()+i,s.end());
- return s;
- }
- }
- }
- int main()
- {
- int t;
- scanf("%d\n",&t);
- while(t--)
- {
- string s;
- cin>>s;
- cout<<nextGreaterNumber(s)<<endl;
- }
- return 0;
- }
Here is the Video: