# Straight Java - Same as Problem 31 - Next Permutation

• A couple of minor things:

1. This problem is almost the same as Next Permutation. The only difference is the given input in an `int` in this problem, instead of `int[]`. Time complexity is O(n).
2. To compare 2 chars, no need to cast to int. We can directly use `char[] digits` and `digits[i] > digits[i - 1]`
``````   public int nextGreaterElement(int n) {
char[] digits = String.valueOf(n).toCharArray();
for (int i = digits.length - 1, j = 0; i > 0; i--)
if (digits[i] > digits[i - 1]) {
for (j = i; j < digits.length; j++)
if (digits[i - 1] >= digits[j]) break;
swap(digits, i - 1, j - 1);
int low = i, hi = digits.length - 1;
while(low < hi) swap(digits, low++, hi--);
break;
}

long res = Long.parseLong(new String(digits));
return res <= Integer.MAX_VALUE && res > n ? (int)res : -1;
}

void swap (char[] nums, int i, int j) {
nums[j] ^= nums[i];
nums[i] ^= nums[j];
nums[j] ^= nums[i];
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.