fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. int pow(int a, int b){
  8. int ans = 1;
  9. for(int i = 1; i <= b; i++)
  10. ans *= a;
  11. return ans;
  12. }
  13.  
  14. int nextGreaterElement(int n) {
  15. string temp = to_string(n);
  16. int len = temp.length();
  17. if(len == 1)
  18. return -1;
  19. int i;
  20. for(i = len-1; i >= 1; i--){
  21. if((temp[i-1]-'0') < (temp[i]-'0'))
  22. break;
  23. }
  24. if(i == 0)
  25. return -1;
  26. i--;
  27. cout<<i<<endl;
  28. int j;
  29. for(j = i+1; j < len && (temp[j]-'0') > (temp[i]-'0'); j++);
  30. j--;
  31. cout<<j<<endl;
  32. char temp1 = temp[i];
  33. temp[i] = temp[j];
  34. temp[j] = temp1;
  35. for(int x = 0; x < len; x++)
  36. cout<<temp[x];
  37. cout<<endl;
  38. string temp2 = temp.substr(i+1,len-1-i);
  39. sort(temp.begin()+i+1,temp.end());
  40. int ans = 0;
  41. for(int i = len-1; i >= 0; i--){
  42. int no1 = temp[i] - '0';
  43. ans += no1*pow(10,len-1-i);
  44. }
  45. return ans;
  46. }
  47.  
  48. int main(){
  49. int n = 21;
  50. cout<<nextGreaterElement(n)<<endl;
  51. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
-1