400. Nth Digit(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83795094

题目:

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 `s`  equence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 
0, which is part of the number 10.

解释:
题目很好理解,是个找规律的数学题。首先记录len位数的个数,其中一位数是从1 开始的:
1~9 9个
10~99 90个
100~999 900个
count=9,90,900,n-count
len 记录当前的位数
start记录当前循环区间的第一个数字
n每次循环都减去 len*count(一共有countlen 位数),设剩下的数字的个数为m(其实在这里就是n了),index为目标数字在该区间的坐标(目标数字就是我们想要找的那一位所属于的数字)则:
m∈[1,len]->index==0
m∈[len+1,2*len]->index==1
m∈[2*len+1,3*len]->index==2
……
所以(n-1)/len就是目标数字在该区间里的坐标(因为坐标是从0开始的,所以需要-1),加上start就是得到了目标数字,然后我们将目标数字转为字符串,index=(n-1)%len就是所要求的目标位。
python代码:

class Solution(object):
    def findNthDigit(self, n):
        """
        :type n: int
        :rtype: int
        """
        count=9
        start=1
        _len=1
        while n>(count*_len):
            n-=(_len*count)
            count*=10
            _len+=1
            start*=10
        target_num=start+(n-1)/_len
        return int(str(target_num)[(n-1)%_len])

c++代码:

class Solution {
public:
    int findNthDigit(int n) {
        int start=1;
        int count=9;
        int len=1;
        int product=count*len;
        while(n-product>0&&product>0)
        {
            n-=(count*len);
            count*=10;
            len+=1;
            start*=10;
            product=count*len;  
        }
        int target_num=start+(n-1)/len;
        return to_string(target_num)[(n-1)%len]-'0';
    }
};

c++要注意product的取值范围,如果超出范围会变成负数,所以需要先判断一下是不是负数。
总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83795094