下面的代码用于取4和2的中点,说明位移运算符优先级低于加减:
1 public class test { 2 public static void main(String[] args) { 3 System.out.println(2+(4-2)>>1); 4 } 5 }
输出:2
而正确的写法如下所示:
1 public class test { 2 public static void main(String[] args) { 3 System.out.println(2+((4-2)>>1)); 4 } 5 }
输出:3
一般取中点的操作我们写为
1 mid = low + ((high-low)>>1)
而不是
mid = (high+low)>>1
是考虑到了有可能会溢出的情况。