class Solution {
public:
int nextGreaterElement(int n) {
string str = to_string(n);
int len = str.length();
int index = -1;
for (int i = len - 1; i >= 0; i--) {
if (str[i] < str[i + 1]) {
index = i;
break;
}
}
if (index == -1) {
return -1;
}
for (int i = len; i >= index; i--) {
if (str[i] > str[index]) {
swap(str[i], str[index]);
break;
}
}
reverse(str.begin() + index + 1, str.end());
long long res = stoll(str);
return res > INT_MAX ? -1 : res;
}
};