Leetcode 400. Nth Digit

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Nth Digit

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int findNthDigit(int n) {
int digits = 1;
long base = 9;
while(n > digits * base) {
n -= digits * base;
digits++;
base *= 10;
}
int residual = n % digits;
int quotient = n / digits;
int target = base / 9 + quotient + (residual?1:0) - 1;
if(residual == 0) {
return target % 10;
}
char s = to_string(target)[residual - 1];
return s - '0';
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int findNthDigit(int n) {
int digits = 1;
long base = 9;
while(n > digits * base) {
n -= digits * base;
digits++;
base *= 10;
}
int residual = n % digits;
int quotient = n / digits;
int target = base / 9 + quotient + (residual?1:0) - 1;
int count = digits - residual + 1;
if(residual == 0) {
return target % 10;
}
int result = 0;
while(count) {
result = target % 10;
target /= 10;
count--;
}
return result;
}
};

Reference

  1. https://leetcode.com/problems/nth-digit/description/
如果有收获,可以请我喝杯咖啡!