The sword refers to Offer 44. The number of a certain digit in the number sequence (C++) Iteration + Integer/Remainder

Numbers are serialized into a character sequence in the format of 0123456789101112131415... In this sequence, the 5th bit (counting from subscript 0) is 5, the 13th bit is 1, the 19th bit is 4, and so on.
Please write a function to find the number corresponding to any nth digit.
Note: "Numbers are serialized in the format of 0123456789101112131415..." : The law of numbers starts with 0, then the number on the right increases by one, and gradually increases to a very large number

Example 1:

输入:n = 3
输出:3

Example 2:

输入:n = 11
输出:0

Restrictions:
0 <= n <2^31
Note: This question is the same as the main site 400 question: https://leetcode-cn.com/problems/nth-digit/

Problem-solving ideas:

1. Call each digit in 101112... as a digit and record it as n;
2. Call 10,11,12,... as a number and record it as num;
3. The number 10 is a two-digit number, which is called this number. The number of digits is 2, which is recorded as digit;
4. The starting number of each digit (ie: 1,10,100,...) is recorded as start.

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

Insert picture description here
Insert picture description here
Insert picture description here

class Solution {
    
    
public:
    int findNthDigit(int n) {
    
    
        // digit表示几位数,start表示几位数的起始数字
        // start*9表示几位数有几个,count=9*start*digit表示几位数总共有几位
        long digit = 1,start = 1,count = 9;
        // 确定所求的数是几位数
        while(n > count){
    
    
            n -= count;//n=n-count;
            start *= 10; //1,10,100
            digit += 1;  //1,2,3
            count = 9 * start * digit;
        }
        long num = start + (n-1)/digit;//确定n所在的数字
        int res = int(to_string(num)[(n-1) % digit] - '0');//(n-1) % digit求余数,
        //表示 确定n在 num 的哪一数位(从第0位开始计数,所以有n-1);
        // - '0' 是把字符串转换成 整型int的操作,可以理解为 ASCII 码相减
        //to_string 将数值转化为字符串。返回对应的字符串。
        return res;
    }
};

Insert picture description here

Author: jyd
link: https: //leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/solution/mian-shi-ti-44 -shu-zi-xu-lie-zhong-mou-yi-wei-de-6/
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114762722