forked from zhedahht/CodingInterviewChinese2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDigitsInSequence.cpp
96 lines (78 loc) · 2.21 KB
/
DigitsInSequence.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题44:数字序列中某一位的数字
// 题目:数字以0123456789101112131415…的格式序列化到一个字符序列中。在这
// 个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。请写一
// 个函数求任意位对应的数字。
#include <iostream>
#include <algorithm>
using namespace std;
int countOfIntegers(int digits);
int digitAtIndex(int index, int digits);
int beginNumber(int digits);
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 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);
}
// ====================测试代码====================
void test(const char* testName, int inputIndex, int expectedOutput)
{
if(digitAtIndex(inputIndex) == expectedOutput)
cout << testName << " passed." << endl;
else
cout << testName << " FAILED." << endl;
}
int main()
{
test("Test1", 0, 0);
test("Test2", 1, 1);
test("Test3", 9, 9);
test("Test4", 10, 1);
test("Test5", 189, 9); // 数字99的最后一位,9
test("Test6", 190, 1); // 数字100的第一位,1
test("Test7", 1000, 3); // 数字370的第一位,3
test("Test8", 1001, 7); // 数字370的第二位,7
test("Test9", 1002, 0); // 数字370的第三位,0
return 0;
}