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 sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
题目大意:
按照序列1,2,...,9,10,11,计算第n个数字指向的值。如n=9指向9,n=11指向0.
理 解:
开始觉得这个题目很难,大致看了其他人的做法,尝试自己去想通这个过程,发现还是比较容易的。
n<10时,返回n。
计算n对应的十进制序列的位数length,再计算它超过该十进制初始值多少位lastN,计算它指向的十进制数,再取得执向的具体某位的值。
代 码 C++:
class Solution { public: int findNthDigit(int n) { if (n < 10) return n; int length = 0, lastN, base, index; while (n > 0) { // 计算n对应的10进制区间,即位数 lastN = n; n = n - 9 *(length+1)*pow(10, length); length++; } base = lastN / length + pow(10, length - 1); // 计算n指向的十进制数 index = lastN % length; // 计算n指向十进制数的第几位 if(index==0){ base = base - 1; index = length; } base = base / pow(10, length - index); base = base % 10; // 获取指向的数字。 return base; } };
运行结果:
原文:https://www.cnblogs.com/lpomeloz/p/11055291.html