C++版 - Leetcode 400. Nth Digit解题报告
leetcode 400. Nth Digit
在线提交网址: https://leetcode.com/problems/nth-digit/
- Total Accepted: 4356
- Total Submissions: 14245
- Difficulty: Easy
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.
Tags: Math
分析:
1.1位数共有9=9·1个, 1~9;
2.2位数共有90=9·10个, 10~99;
3.3位数共有900=9·10·10个, 100~999;
…
已AC代码:
#include<cstdio>
#include<iostream>
using namespace std;
class Solution {
public:
int findNthDigit(int n) {
int len = 1, base = 1; // len表示当前数的位数, base表示当前位是个位、百位、千位等...
while (n > 9L * base * len) {
n -= 9 * base * len;
len++;
base *= 10;
}
int curNum = (n - 1)/len + base, digit = 0; // curNum是含有所找digit的那个数
for (int i = (n - 1) % len; i < len; ++i) { // 根据偏移量找到所找的数字
digit = curNum % 10;
curNum /= 10;
}
return digit;
}
};
// 以下为测试
int main() {
Solution sol;
int n;
cin>>n; // 150
int res = sol.findNthDigit(n);
cout<<res<<" "<<endl;
return 0;
}