[Leetcode] 400. Nth Digit 解题报告

来源:互联网 发布:淘宝卖办公用品 编辑:程序博客网 时间:2024/06/07 19:07

题目

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:3Output:3

Example 2:

Input:11Output:0Explanation: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.

思路

可以分为三步来计算:1)找出给定的n落在几位数的范围内;2)找出具体落在哪个数字上;3)找出具体在哪一位上。

一位数一共有9个,两位数一共有90个,三位数一共有900个,以此类推,因此可以每增加一位数字,看n是否在这个范围之内。我们以n = 150为例来具体说明:1)首先一位数有9个数字并且9 < 150,所以位数可以加1,这样 n - 9 = 141,然后两位数的数字有2 * 90 = 180位,大于141,所以目标数字肯定是在两位数上。2)求具体数字,可以用10 + (141 - 1) / 2 = 80求出。3)最后求具体落在哪一位上,可以用(141 - 1) % 2 = 0求出为第0位,即8。思路挺直观,可是要写出bug free的代码却不是那么容易。

代码

class Solution {public:    int findNthDigit(int n) {        long digit = 1, ith = 1, base = 9;        while(n > base * digit) {            n -= base * digit;            ++digit;            ith += base;        // the accumulated number            base *= 10;        }        string s = to_string(ith + (n - 1)/digit);        return s[(n - 1) % digit] - '0';    }};

原创粉丝点击