leetcode 400. Nth Digit

題目不難,但是debug了半天。 

1. 時刻注意溢出和邊界問題

2. 當sequence從1開始,還是從0開始,這是個問題。。。

class Solution {
public:
    int findNthDigit(int n) {
        long cnt = 9, // 時刻注意溢出問題
            num = 1;
        while (n > cnt * num){
            n -= cnt * num;
            cnt *= 10;
            num++;
        }
        long targetNum = 1;
        for (int j = 1; j < num; ++j)
            targetNum *= 10;
        n--; // 這一步,使得sequence從0 開始,而不是從1開始,便於接下來的計算
        targetNum += (n / num);
        n %= num; 
        string str = to_string(targetNum);
        return str[n] - '0';
    }
};


發佈了88 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章