400. Nth Digit

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

Note: n is positive and will fit within the range of a 32-bit signed integer (n < 2^31).

Example 1:

Input: 3
Output: 3

Example 1:

Input: 11

Output: 0

Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 
is a 0, which is part of the number 10.

Solution:

class Solution {
public:
    int findNthDigit(int n) {
        if(n <= 9) return n;
        int s=1,i=1,j=9,base=0;
        while(n>j && s<8){
            s++;
            i*=10;
            j=j+s*i*9;
        }
        if(s == 8 && n > j){
            s++;
            i*=10;
            base = j;
        }else{
            base = j - s * i * 9;
        }
        int offset = n - base - 1;
        int target = i + offset / s;
        int index = offset % s;
        return to_string(target)[index] - '0';
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,789评论 0 33
  • 问题: Find the nth digit of the infinite integer sequence 1...
    Cloudox_阅读 796评论 0 0
  • No.1 猪肉 No.2 牛肉 No.3 鸡肉 No.4 鱼肉 No.5 内脏
    DoubleMia阅读 192评论 0 0
  • 阳光明媚,上海艺大开学了。颜笑和她的发小陈杏进入了校园,看着一个个充满生机的生命,看着一个个背负着希望的...
    明若轻溪阅读 146评论 0 1
  • 日精进,2017年6月6日 星期二 第190篇 “低调做事,忠心为民心!”这是一位企业家朋友的原则。 ...
    李文燊阅读 188评论 0 0