# 从二分搜索实现中的一个 bug 说起

··1329 words·3 mins·
Programming C++ Algorithms Search

# 一道二分搜索问题#

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.

Suppose you have n versions [1, 2, …, n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

``````int firstBadVersion(int n) {
int head = 1, tail = n;
int mid = (head + tail) / 2;
tail = mid;
} else {
}
}
}
``````

``````int mid = (head + tail)/2;
``````

``````int mid = head + (tail - head)/2;
``````

# 当溢出发生，到底会发生什么？#

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined, unless such an expression is a constant expression, in which case the program is ill-formed. [Note: most existing implementations of C++ ignore integer overflows].

This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.

``````#include <iostream>
#include <limits>
using namespace std;

int main(){
unsigned int num = std::numeric_limits<unsigned int>::max();

for (int i = 1; i <= 3; i++){
unsigned result = num + i;
cout << result << (i==3?'\n':' ');
}

return 0;
}
``````

``````0 1 2
``````

(全文完)

# 参考#

## Related

Static and Dynamic Linkage in C++
·387 words·2 mins
Programming C++
Pretty Output Format in C++
··233 words·2 mins
Programming C++
Build C++ Project with CMake -- A Simple Example
·551 words·3 mins
Programming C++ CMake OpenCV