判断奇偶
一,介绍
实际开发中,判断奇偶是很常见的场景。
二,开发
1,%取余
private static void judgeEven1(int i) { if (i % 2 == 0) { System.out.print(i + "是偶数。"); } else { System.out.print(i + "是奇数"); } }
能被2整除的是偶数
2,&操作
private static void judgeEven2(int i) { if ((i & 1) == 0) { System.out.print(i + "是偶数。"); } else { System.out.print(i + "是奇数"); } }
利用二进制与操作,偶数与为0,同样异或也可以
3,位移操作
private static void judgeEven3(int i) { if ((i >> 1 << 1) == i) { System.out.print(i + "是偶数。"); } else { System.out.print(i + "是奇数"); } }
先向右移1位,相当于除以2,再向左移1位,相当于乘以2,如果数字不变,则为偶数
三,性能
public static void main(String[] args) { int count = 50000000; Stopwatch stopwatch1 = Stopwatch.createStarted(); for (int i = 0; i < count; i++) { judgeEven1(i); } System.out.println(); System.out.println(stopwatch1); Stopwatch stopwatch2 = Stopwatch.createStarted(); for (int i = 0; i < count; i++) { judgeEven2(i); } System.out.println(); System.out.println(stopwatch2); Stopwatch stopwatch3 = Stopwatch.createStarted(); for (int i = 0; i < count; i++) { judgeEven3(i); } System.out.println(); System.out.println(stopwatch3); }
分析,计算机移位操作最快,其次是与,最后是取余
结果:
可以看出性能有差距,但在实际开发中纯粹的判断奇偶性能基本无差,就当时语法糖吧。