Leetcode278. 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.
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.
解题分析
这道题目,第一感觉给人非常简单,就是一道典型的二分查找的题目。但是这里面有一个坑,是我之前没有注意过的。
我们都知道二分查找用一个头指针和尾指针来指示两个元素,通过求中间位置的元素来进行递归查找。假设头指针为start,尾指针为end,那么显而易见中间位置mid=(start+end)/2。乍一看好像是对的,但其实忽略了一个非常重要的问题。如果end非常大(比如2^31-1),那么显然start+end就会超过2^31-1从而导致溢出,进而出现runtime error的情况。
那么应该怎么解决这个问题呢?我们稍微调整一下,改成mid=start+(end-start)/2就完美避开了溢出这个问题。
源代码
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int start = 1, end = n, mid;
while (start < end) {
mid = start + (end - start) / 2;
if (isBadVersion(mid)) {
end = mid;
}
else {
start = mid + 1;
}
}
return start;
}
};
Leetcode7. Reverse Integer
题目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
解题分析
这道题乍一看也是非常简单,通过除法和取余操作就可以解决。但题目也提示我们要考虑溢出的情况。因此,这就涉及到了一个问题,如何判断溢出。
我们知道当int溢出时会自动转成int最小的数(也即-2^32),因此我们可以利用这一点,判断理论上获得的值与现在的值是否相同,如果不同,说明溢出发生了;其它的就没什么问题了。
源代码
class Solution {
public:
int reverse(int x) {
int number = 0;
while(x != 0) {
int bit = x % 10;
int result = number * 10 + bit;
if((result - bit) / 10 != number) {
return 0;
}
number = result;
x /= 10;
}
return number;
}
};
以上是我对两道溢出问题的一些想法,有问题还请在评论区讨论留言~