LeetCode #1291 Sequential Digits 連續數字

英文原文如下

An integer has sequential digits if and only if each digit in the number is one more than the previous digit.

Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.

中文翻譯

「連續數字」是指當數字中的每個位數都比前一位數多一時。

返回一個排序後的串列,其中包含範圍[low, high](包括low和high)內所有具有連續數字的整數。

範例及題目限制

💡Hint 1 提示1

Generate all numbers with sequential digits and check if they are in the given range.

生成所有具有連續數字的數字,並檢查它們是否在給定的範圍內。

💡Hint 2 提示2

Fix the starting digit then do a recursion that tries to append all valid digits.

固定起始數字,然後進行遞迴,嘗試往後添加所有有效的數字。


解題思路

在我們的解法中,我們用了low 跟 high的長度(位數) 來控制while迴圈

C# 解決方案

方案1

public class Solution {
    public IList<int> SequentialDigits(int low, int high) {
        List<int> res = new List<int>();

        int len = low.ToString().Length;
        int highLen = high.ToString().Length;
        int startNum = 1;
        while (true) {
            if(startNum+len<=10){
                int num = genNum(startNum, len);
                if (num > high){
                    break;
                }
                if (num >= low && num <= high){
                    res.Add(num);
                }
            }
            
            if(startNum == 9){
                startNum = 1;
                len+=1;
            }
            else{
                startNum+=1;
            }

            if(len>highLen){
                break;
            }
        }

        return res;
    }

    private int genNum(int start, int length) {
        int result = 0;
        int curr = start;
        for (int i = 0; i < length; i++) {
            result = result * 10 + curr;
            if (curr == 9){
                break;
            }
            curr+=1;
        }
        return result;
    }
}

可以看出是使用genNum來創造特定長度的連續數字

另外,在while迴圈中,用了 startNum+len<=10 來判斷,主要就是為了判斷長度是否可以組成連續字串

像是從 1 開始的連續字串,最多只能9位對吧 >> 123456789

那要是要求10位數,那是無法達成的


結論

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Sequential Digits – LeetCode

一些隨機的LeetCode文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *