Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

why left+(right-left)/2 will not overflow?

9

//Suppose (to make the example easier) the maximum integer is 100, 
//left = 50, and right = 80. If you use the naive formula:

int mid = (left + right)/2;
//the addition will result in 130, which overflows.

//If you instead do:

int mid = left + (right - left)/2;
//you can't overflow in (right - left) because you're subtracting 
//a smaller number from a larger number. 
//That always results in an even smaller number, so it can't 
//possibly go over the maximum. E.g. 80 - 50 = 30.

//And since the result is the average of left and right, 
//it must be between them. Since these are both less than the maximum integer, 
//anything between them is also less than the maximum, so there's no overflow.
Comment

PREVIOUS NEXT
Code Example
Java :: Java Stack class push() method 
Java :: sudoku generator java code 
Java :: reset a jTable without deleting rows 
Java :: rerun main method 
Java :: Maven test failure sure fire solved 
Java :: control statements 
Java :: sartt timer of 40 second when send otp andrpid 
Java :: how to know when user is done typing android 
Java :: Write program for problem 1 such that every regex runs as its own thread in java 
Java :: java tostring methode überschreiben 
Java :: java ordenar los valores de un array de menor a mayor 
Java :: join table in where clause criteria in java hibernate 
Java :: java writing an object 
Java :: custom class level annotation in spring 
Java :: simple example of adding two number by calling a method 
Java :: crazy error 
Java :: Java Stack class empty() method 
Java :: java @documented 
Java :: set countdown timer to play audio file android studio 
Java :: java remove element from list 
Java :: at com.rezafirstapp.simplediceroller.MainActivity$2.run(MainActivity.java:56) at java.lang.Thread.run(Thread.java:923) 
Java :: JVM signatures 
Java :: Rotate array to left k cells python 
Java :: xml definition file for spring 
Java :: Java Floating-point Literals 
Java :: Java program to find largest of three numbers using nested if 
Java :: intellij run single java file 
Java :: es java painless source int value increase 
Java :: java multiple implements 
Java :: Android equivalent of getElementById 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =