We would like to double an int value without using arithmetic operator or function in Java.
For example, we would like to double value 2 to 4, and 4 to 8.
And we cannot use * or + or Math.pow()
function.
// Left shifting as a quick way to multiply by 2. public class Main { public static void main(String args[]) { int num = 5; num = num << 1; System.out.println(num); num = num << 1; System.out.println(num); num = num << 1; System.out.println(num); } }
Since each left shift has the effect of doubling the original value, we can use left shift as a way to multiply by 2.
If you shift a 1 bit into the high-order position (bit 31 for int or 63 for long), the value will become negative.