400. Nth Digit

Description

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 < 231).

Example 1:
Input:
3
Output:
3

Example 2:
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

Math

很多细节需要注意!

class Solution {
    public int findNthDigit(int n) {
        int len = 1;
        int base = 1;

        while (n > 9L * base * len) {   // watch out for overflow!
            n -= 9 * base * len;
            base *= 10;
            ++len;
        }
        
        // don't forget to minus 1 because base matters
        return getDigit(base + (n - 1) / len, len - (n - 1) % len);
    }
    
    // if n = 6104 and i = 2, return 0
    public int getDigit(int n, int i) {
        while (i > 1) {
            n /= 10;
            --i;
        }
        
        return n % 10;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 李寡妇 六月的天,开始是格外的清明,天空中一些云慢慢的走,接着就连骄傲的太阳也渐渐的陷入云围,再过不久月亮就完...
    钚崽阅读 663评论 0 1
  • 这一刻 莫名的惆怅 没来由的悲伤 似牛毛细雨绵绵 悄无声息 却汇成心泪的河流 捧一滴冰冻的泪水 抚平眼角的细纹 掬...
    金锁记_60ed阅读 235评论 0 1
  • 做了一期小节目(可以收听音频哦)http://mp.weixin.qq.com/s/FX87-BIlAT8XGBd...
    __哈哈__阅读 219评论 0 1
  • 1 大学的时候他是班长,嬉皮笑脸,放荡不羁,能够成为班长,并非是因为他的成绩有多好,而是因为他的口才,两人上一秒还...
    少女陆sunny阅读 1,228评论 6 12
  • http://www.bilibili.com/video/av1654354/ 《浮生一日》 这部以“爱和恐惧”...
    久辞辞辞阅读 366评论 0 0