美文网首页
400-Nth Digit

400-Nth Digit

作者: cocalrush | 来源:发表于2017-04-12 01:43 被阅读0次

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

这道题有点意思

    public int findNthDigit(int n) {
        long i = 0;
        int start = 1;
        int len = 1;
        long val = 9; //注意溢出
        
        //找到落在哪个区域
        while(n > ( i = len * val)){
            n -= i; //注意溢出?
            len ++;
            val = val * 10;
            start = start * 10;
        }
        
        //找到对应数字是多少
        int num = start + (n - 1)/len;
        
            //找到对应数字的位数
        String s = Integer.toString(num);
        return Character.getNumericValue(s.charAt((n - 1) % len));
        
    }

相关文章

网友评论

      本文标题:400-Nth Digit

      本文链接:https://www.haomeiwen.com/subject/qoypattx.html