Given a 32-bit positive integer n, you need to find the smallest 32-bit integer that has exactly the same number of bits present in n and whose value is greater than n. Returns -1 if no such 32-bit integer exists.
Example 1:
Input: 12 Output: 21
Example 2:
Input: 21 Output: -1
People feel that this question is simpler than ii. The
idea is: starting from the status, find the position where the number is smaller than the previous digit. This position is to be replaced with
which position of the number to exchange? Swap with the number that is greater than and closest to its position, which ensures that its value is greater than the original and closest to it
1 #include<iostream> 2 class Solution { 3 public: 4 static bool cmp(int a, int b){return a > b;} 5 int nextGreaterElement(int n) { 6 vector<int> digit; 7 int temp = 0, t = n; 8 while(n){ 9 digit.push_back(n%10); 10 n /= 10; 11 } 12 int len = digit.size(), i; 13 for (i = 1 ; i < len; i++ ){//find the position to be swapped 14 if (digit[i] < digit[i- 1 ]) 15 break ; 16 } 17 sort(digit.begin(), digit.begin()+ i, cmp); 18 for ( int k = i- 1 ; k >= 0 ; k-- ){ 19 if (digit[ k] > digit[i]){//find the swap position 20 swap(digit[k], digit[i]); 21 break; 22 } 23 } 24 for(int j = len-1; j >= 0; j--) temp = temp*10 + digit[j]; 25 temp = (temp>t) ? temp : -1; 26 return temp; 27 } 28 };