-
Notifications
You must be signed in to change notification settings - Fork 0
/
digitAtIndex.cpp
52 lines (39 loc) · 1004 Bytes
/
digitAtIndex.cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <cmath>
using namespace std;
int beginNumber(int digits);
int countOfIntegers(int digits) {
if (digits == 1)
return 10;
int count = (int) std::pow(10, digits-1);
return 9 * count;
}
int digitAtIndex(int index, int digits) {
int number = beginNumber(digits) + index / digits;
int indexFromRight = digits - index % digits;
for (int i = 1; i < indexFromRight; i++)
number /= 10;
return number % 10;
}
int beginNumber(int digits) {
if (digits == 1)
return 0;
return (int)std::pow(10, digits-1);
}
int digitAtIndex(int index) {
if (index < 0)
return -1;
int digits = 1;
while (true) {
int numbers = countOfIntegers(digits);
if (index < numbers * digits)
return digitAtIndex(index, digits);
index -= digits * numbers;
digits++;
}
return -1;
}
int main() {
cout << digitAtIndex(1001) << endl;
return 0;
}