A next greater element LeetCode 556. III (Next Greater Element III)

A next greater element 556. III
556. In the Next the Greater the Element III

Title Description
Given a 32-bit positive integer n, you need to find a minimum 32-bit integer, which is the same as the number of bits n in the presence and the value greater than n. If such does not exist 32-bit integer, return -1.

LeetCode556. Next Greater Element III中等

Example 1:

Input: 12
Output: 21

Example 2:

Input: 21
Output: -1

Example 3:

Input: 12,443,322
Output: 13,222,344

Java implementation

import java.util.Arrays;

class Solution {
    public int nextGreaterElement(int n) {
        char[] nums = Integer.toString(n).toCharArray();
        int i, j, len = nums.length;
        for (i = len - 1; i > 0; --i) {
            if (nums[i] > nums[i - 1]) {
                break;
            }
        }
        if (i == 0) {
            return -1;
        }
        System.out.println(i);
        for (j = len - 1; j >= i; --j) {
            if (nums[j] > nums[i - 1]) {
                char temp = nums[j];
                nums[j] = nums[i - 1];
                nums[i - 1] = temp;
                break;
            }
        }
        Arrays.sort(nums, i, len);
        long val = Long.parseLong(new String(nums));
        return val > Integer.MAX_VALUE ? -1 : (int) val;
    }
}

Similar topics

Reference material

Guess you like

Origin www.cnblogs.com/hglibin/p/10988070.html