@RunRunCode It's just a "simple" way to convert a number to a string. It will call String.valueOf(n) explicitely anyway. So I would suggest to use either String.valueOf or Integer.toString instead.

class Solution {
public:
int nextGreaterElement(int n) {
string temp = to_string(n);
stack<int> stk;
int prev=0;
for (int i=temp.size()-1;i>=0;i--){
if (!stk.empty() && temp[i]<temp[stk.top()]){
//find the next smallest number greater than the current element.
//swap these two numbers and reverse the later part to keep it minimum
while (!stk.empty() && temp[i]<temp[stk.top()]){
prev = stk.top();
stk.pop();
}
swap(temp[i], temp[prev]);
reverse(temp.begin()+i+1, temp.end());
break;
}
stk.push(i);
}
long long res = stoll(temp);
return (res>INT_MAX || (int)res==n)?-1:(int)res;
}
};

Made a slight change on finding the minIdx (AKA, the index of the smallest number that is larger than the current digit):

//set minIdx to be current digit
int minIdx = i;
//find the first digit that is greater than current digit
for (int k = i; k < num.length; ++k) {
if (num[k] > num[minIdx]){
minIdx = k;
break;
}
}
//continue to search if this index is "minimal", if not, update
for(int j = i+1; j < num.length; j++) {
if (num[j] > num[i] && minIdx != i && num[j] < num[minIdx])
minIdx = j;
}

@szhu3210 Could change the inner if statement to this. It will be faster and would change the solution from O(nlogn) to O(n)

if t[j]>t[0]:
t[0],t[j]=t[j],t[0]
t[1:]=reversed(t[1:])
res = int(num[:i] + ''.join(t))
return res if res <= (2**31-1) else -1
#or even faster:
x,y=1,len(t)-1
while x<y:
t[x],t[y]=t[y],t[x]
x+=1
y-=1