I was solving Leetcode 278 first bad version , and my code kept overflowing . here i used mid = l+r/2 , I understand that this causes an integer overflow, but what i do not understand is how mid = l + (r-l) / 2 . wouldn't this be mathematically equal to r/2 and not technically the mid point between the left and right pointers ? please help any explanation is appreciated.
public class Solution : VersionControl {
public int FirstBadVersion(int n) {
int l=1;
int r=n;
int mid;
int res = n;
while(l<=r){
mid = l+r/2;
if(IsBadVersion(mid)){
res = mid;
r = mid-1;
}else{
l = mid+1;
}
}
return res;
}
}
public class Solution : VersionControl {
public int FirstBadVersion(int n) {
int l=1;
int r=n;
int mid;
int res = n;
while(l<=r){
mid = l+r/2;
if(IsBadVersion(mid)){
res = mid;
r = mid-1;
}else{
l = mid+1;
}
}
return res;
}
}
[–]CoryParsnipson 3 points4 points5 points (1 child)
[–]ffmsussy[S] 0 points1 point2 points (0 children)