Skip to content

Commit

Permalink
Merge pull request neetcode-gh#3170 from RaafatAkkad/patch-1
Browse files Browse the repository at this point in the history
Fix integer overflow in java/0704-binary-search.java
  • Loading branch information
a93a authored Dec 19, 2023
2 parents 8f72245 + bb0fa0c commit d715a99
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion java/0704-binary-search.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ public int search(int[] nums, int target) {
int j = nums.length - 1;

while (i <= j) {
int mid = (i + j) / 2;
// mid is calculated this way to prevent integer overflow.
// See: https://blog.research.google/2006/06/extra-extra-read-all-about-it-nearly.html
int mid = i + (j - i) / 2;

if (nums[mid] == target) return mid; else if (
nums[mid] < target
Expand Down

0 comments on commit d715a99

Please sign in to comment.