-
Notifications
You must be signed in to change notification settings - Fork 0
/
first_bad_version.cpp
89 lines (82 loc) · 1.9 KB
/
first_bad_version.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
/*
* =====================================================================================
*
* Filename: first_bad_version.cpp
*
* Description: First Bad Version: You are a product manager and currently leading a
* team to develop a new product. Unfortunately, the latest version of
* your product fails the quality check. Since each version is
* developed based on the previous version, all the versions after a
* bad version are also bad.
*
* Version: 1.0
* Created: 08/30/18 11:23:50
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
// Forward declaration of isBadVersion API.
bool isBadVersion(int version)
{
return version >= 4 ? true : false;
}
// Iterative
class Solution1
{
public:
int firstBadVersion(int n)
{
while (isBadVersion(n))
{
n--;
}
while (!isBadVersion(n))
{
n++;
}
return n;
}
};
// Binary search
class Solution2
{
public:
int firstBadVersion(int n)
{
int left = 1;
int right = n;
while (left < right)
{
int mid = ((int64_t)left + right) / 2;
if (isBadVersion(mid))
{
right = mid;
}
else
{
left = mid + 1;
}
}
// left == right
return left;
}
};
using Solution = Solution2;
int main(int argc, char* argv[])
{
int num = 10;
if (argc > 1)
{
num = atoi(argv[1]);
}
int bad_ver = Solution().firstBadVersion(num);
printf("%d -> %d\n", num, bad_ver);
return 0;
}