400-Nth Digit

2017-04-12  本文已影响0人  cocalrush

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));
        
    }
上一篇 下一篇

猜你喜欢

热点阅读