导航

今日头条,找出下一个比它大的整数

Posted on 2018-09-14 20:25  骄阳照林  阅读(458)  评论(0编辑  收藏  举报
package Integer;

import java.util.Arrays;

public class GetNextAsc {

public static int getNextAsc(int obj) {
String temp = obj + "";
char[] chars = temp.toCharArray();
int len = chars.length;
for (int i = 0; (len - i - 2 >= 0) && i < len; i++) {
int maxIndex = -1;
char maxValue = '9' + 1;
//获取最小的大数值下标
for (int r = len - i - 1; r <= len - 1; r++) {
if (chars[r] > chars[len - i - 2]) {
if (chars[r] < maxValue) {
maxIndex = r;
maxValue = chars[r];
}
}
}

if (maxIndex == -1) {
continue;
} else {
//交换
char c = chars[len - i - 2];
chars[len - i - 2] = chars[maxIndex];
chars[maxIndex] = c;
//排序,从小到大
char[] subChar = Arrays.copyOfRange(chars, len - i - 1, len);
Arrays.sort(subChar);
for (int j = 0; j < i + 1; j++) {
int k = len - i - 1 + j;
chars[k] = subChar[j];
}
StringBuilder sb = new StringBuilder();
for (int p = 0; p < chars.length; p++) {
sb.append(chars[p]);
}

return Integer.valueOf(sb.toString());

}

}

return -1;

}

public static void main(String[] args) {
System.out.println(getNextAsc(1111111));
}

}