大於某數的相鄰兩位數不同的最小整數 – 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)); 
    } 

發佈留言