leetcode 400. Nth Digit 从1到n第n位数字是什么 + 找规律
2017-12-06 17:20
423 查看
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 inte
4000
ger (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.
下面是C++的做法
我们首先来分析自然数序列和其位数的关系,前九个数都是1位的,然后10到99总共90个数字都是两位的,100到999这900个数都是三位的,那么这就很有规律了,我们可以定义个变量cnt,初始化为9,然后每次循环扩大10倍,再用一个变量len记录当前循环区间数字的位数,另外再需要一个变量start用来记录当前循环区间的第一个数字,我们n每次循环都减去len*cnt (区间总位数),当n落到某一个确定的区间里了,那么(n-1)/len就是目标数字在该区间里的坐标,加上start就是得到了目标数字,然后我们将目标数字start转为字符串,(n-1)%len就是所要求的目标位,最后别忘了考虑int溢出问题,我们干脆把所有变量都申请为长整型的好了,
代码如下:
Note:
n is positive and will fit within the range of a 32-bit signed inte
4000
ger (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.
下面是C++的做法
我们首先来分析自然数序列和其位数的关系,前九个数都是1位的,然后10到99总共90个数字都是两位的,100到999这900个数都是三位的,那么这就很有规律了,我们可以定义个变量cnt,初始化为9,然后每次循环扩大10倍,再用一个变量len记录当前循环区间数字的位数,另外再需要一个变量start用来记录当前循环区间的第一个数字,我们n每次循环都减去len*cnt (区间总位数),当n落到某一个确定的区间里了,那么(n-1)/len就是目标数字在该区间里的坐标,加上start就是得到了目标数字,然后我们将目标数字start转为字符串,(n-1)%len就是所要求的目标位,最后别忘了考虑int溢出问题,我们干脆把所有变量都申请为长整型的好了,
代码如下:
#include <iostream> #include <vector> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <queue> #include <stack> #include <string> #include <climits> #include <algorithm> #include <sstream> #include <functional> #include <bitset> #include <numeric> #include <cmath> #include <regex> using namespace std; class Solution { public: int findNthDigit(int n) { long long lenOfDit = 1, start = 1, count = 9; while (n > lenOfDit*count) { n -= lenOfDit*count; lenOfDit += 1; count *= 10; start *= 10; } int num = start + (n - 1) / lenOfDit; string s = to_string(num); return s[(n - 1) % lenOfDit] - '0'; } };
相关文章推荐
- Leetcode 400. Nth Digit 第n个数字 解题报告
- leetcode_400. Nth Digit 查找自然数序列中的第n个数字
- leetcode 233. Number of Digit One 从1到n的数组中出现数字1的数量 + 寻找规律,公式计算
- [LeetCode]400. Nth Digit(规律)
- leetcode 400. Nth Digit解题报告
- LeetCode | 400. Nth Digit 数学原理题
- Leetcode 400. Nth Digit[easy]
- LeetCode 400. Nth Digit
- [LeetCode]400. Nth Digit
- Leetcode 400. Nth Digit (Easy) (cpp)
- [Leetcode] 400. Nth Digit 解题报告
- LeetCode400. Nth Digit
- LeetCode 400. Nth Digit
- leetcode -- 459. Repeated Substring Pattern【java细节优化 + 模式规律 + 数字规律排除 】
- (hdu step 4.1.5)find the nth digit(求S串中的第n个位置上是什么数字)
- LeetCode 400. Nth Digit
- LeetCode—400. Nth Digit
- 400. Nth Digit (leetcode) 。。。
- leetcode 400. Nth Digit
- leetcode 400. Nth Digit