今日頭條,找出下一個比它大的整數


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));
}

}

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com