1. 程式人生 > >738. Monotone Increasing Digits

738. Monotone Increasing Digits

Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.

(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)

Example 1:

Input: N = 10
Output: 9

Example 2:

Input:
N = 1234 Output: 1234

Example 3:

Input: N = 332
Output: 299

Note: N is an integer in the range [0, 10^9].

import java.util.ArrayList;
import java.util.List;
class Solution {
    public int monotoneIncreasingDigits(int N) {
        // 提取出整數N各位上的數字
        List<Integer> digits = new ArrayList<>();
        while (N >= 10) {
            digits.add(0,N%10);
            N /= 10;
        }
        digits.add(0, N);

        // 檢查當前各位數字是否遞增
        while (!checkValid(digits)) {
            // 如遇到非遞增的情況,調整
            transform(digits);
        }
        // 若首位數字為0,刪除
        while (digits.get(0) == 0) {
            digits.remove(0);
        }
        // 將各位上的數字組裝成一個整數
        String strResult = "";
        for (int dgt :digits) {
            strResult += dgt;
        }
        return Integer.valueOf(strResult);
    }

    private void transform(List<Integer> digits) {
        int pre = digits.get(0);
        // 從首向尾遍歷,找出首次出現非遞增的一對數
        for (int i = 1; i < digits.size(); i++) {
            if (digits.get(i) < pre) {
                digits.set(i-1, pre-1);
                for (int j = i; j < digits.size(); j++) {
                    digits.set(j, 9);
                }
                break;
            }
            pre = digits.get(i);
        }
    }

    // 檢查是否遞增
    private boolean checkValid(List<Integer> digits) {
        int pre = -1;
        for (int d : digits) {
            if (pre > d) {
                return false;
            }
            pre = d;
        }
        return true;
    }
}