1. 程式人生 > >[LeetCode] 738. Monotone Increasing Digits

[LeetCode] 738. Monotone Increasing Digits

tput 扯淡 ret NPU 就是 pan 個數 leetcode solution

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].

題意:給一個數字,找出比它小最接近它的 非遞減數 例如 1234,122 ,266等等

這題其實不難,關鍵在找到最近的遞減數的位置,而且我們得倒著去找,為什麽呢?因為會有像是222000這種扯淡的數字,所以我們得一邊找一邊操作

之後就是這個位置之後的數字都改為9就行了

唉,寫的時候被自己蠢哭了,一開始一直都是用String,寫著寫著發現String是不可變的,中間加了一堆中間變量操作

後來想想,用char[] 就可以了啊

class Solution {
    private int toInt(char[] chs) {
        int res = 0;
        for (int i = 0; i < chs.length; i++)
            res = res*10 + (chs[i] - ‘0‘);
        return res;
    }
    public int monotoneIncreasingDigits(int N) {
        String str = String.valueOf(N);
        
int n = str.length(), j = n; char[] chs = str.toCharArray(); for (int i = n - 1; i > 0; i--) { if (chs[i] < chs[i - 1]) { chs[i - 1]--; j = i; } } for (int i = j; i < n; i++) { chs[i] = ‘9‘; } return toInt(chs); } }

[LeetCode] 738. Monotone Increasing Digits