当前位置:编程学习 > JAVA >>

大于某数的相邻两位数不同的最小整数

题目简述:求大于某个整数n的相邻两位数不同的最小的整数。
 
Java代码 
public class test { 
 
    public static void main(String[] args) { 
        // int num = (int) (Math.random() * 10000000); 
        int num = 9899; 
        System.out.println(num); 
        System.out.println(getResult(num)); 
    } 
 
    private static int getResult(int num) { 
        char[] array = String.valueOf(num).toCharArray(); 
        int length = array.length; 
        int from = 1; 
        while (from < length) { 
            // 找到首个跟上一位重复的位置 
            if (array[from] == array[from - 1]) { 
                // 回退,找得首个不为9的位置 
                while (from >= 0 && array[from] == '9') { 
                    from--; 
                } 
                // 如果第一位就是9,原数前面加一位1 
                if (from < 0) { 
                    array = ('1' + String.valueOf(num)).toCharArray(); 
                    length++; 
                    from = 1; 
                    break; 
                } 
                array[from] = (char) (array[from] + 1); 
                // 如果改改后与上一位不同 
                if (array[from] != array[from - 1]) { 
                    from = from + 1; 
                    break; 
                } 
            } else { 
                from++; 
            } 
        } 
        // 如果原数无重复,则+1 
        if (from == length) { 
            num++; 
            array = String.valueOf(num).toCharArray(); 
            length = array.length; 
            if (length > 1 && array[length - 2] == array[length - 1]) { 
                return getResult(num); 
            } 
            return num; 
        } 
 
        // 从改变位的下一位开始,0、1序列填充 
        char c = '0'; 
        int s = '0' + '1'; 
        for (; from < length; from++) { 
            array[from] = c; 
            c = (char) (s - c); 
        } 
 
        return Integer.valueOf(String.valueOf(array)); 
    } 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,