LeetCode - 400. Nth Digit
2017-03-31 15:24
375 查看
解题代码:
classSolution {
public:
int findNthDigit(int n) {
long i=1,t=9;
while(n>t*i){
n-=t*i;
i++;
t*=10;
}
int a=n/i,b=n%i;
long res=1;
for(int j=0;j<i-1;j++)
res*=10;
res=res+a-1;
if(b==0)
return res%10;
else{
res++;
for(int j=0;j<i-b;j++)
res/=10;
return res%10;
}
}
};
解题思路:
题目要求返回序列1,2,3……中第n位的数据。经分析可知,1~9共9个一位,10~99共90个两位,100~999共900个三位,依次类推。可以此判断出第n位属于哪一个区间,对应所在的数字共有多少位,然后根据n减去前面的区间共有的位数,可得到它在该区间的第几位。而又因为知道它在这一区间中每个数字共几位,最后便可凭此得到所求的结果。
classSolution {
public:
int findNthDigit(int n) {
long i=1,t=9;
while(n>t*i){
n-=t*i;
i++;
t*=10;
}
int a=n/i,b=n%i;
long res=1;
for(int j=0;j<i-1;j++)
res*=10;
res=res+a-1;
if(b==0)
return res%10;
else{
res++;
for(int j=0;j<i-b;j++)
res/=10;
return res%10;
}
}
};
解题思路:
题目要求返回序列1,2,3……中第n位的数据。经分析可知,1~9共9个一位,10~99共90个两位,100~999共900个三位,依次类推。可以此判断出第n位属于哪一个区间,对应所在的数字共有多少位,然后根据n减去前面的区间共有的位数,可得到它在该区间的第几位。而又因为知道它在这一区间中每个数字共几位,最后便可凭此得到所求的结果。
相关文章推荐
- LeetCode 400. Nth Digit
- [Leetcode] 400. Nth Digit 解题报告
- [leetcode] 400. Nth Digit 解题报告
- LeetCode—400. Nth Digit
- [LeetCode]--400. Nth Digit
- LeetCode 400. Nth Digit
- leetcode 400. Nth Digit
- [LeetCode]400. Nth Digit(规律)
- 400. Nth Digit (leetcode) 。。。
- Leetcode 400. Nth Digit 第n个数字 解题报告
- LeetCode 400. Nth Digit
- LeetCode400. Nth Digit
- 【leetcode】400. Nth Digit(Python & C++)
- LeetCode 400. Nth Digit
- [leetcode: Python]400. Nth Digit
- 【Leetcode】400. Nth Digit
- [LeetCode]400. Nth Digit
- leetcode 400. Nth Digit
- Leetcode 400. Nth Digit[easy]
- 【LeetCode】 400. Nth Digit