[声明]所有代码均来自Joshua Bloch和Neal Gafter所著的<Java解惑>一书,本人仅因学习需要摘抄和注释,感谢二位作者的知识分享.
代码:
public class Oddity { public static boolean isOdd(int i) { return i % 2 == 1; } public static void main(String[] args) { int i = 4; System.out.println("Question: " + i + " is odd ? "); System.out.println("Answer: " + isOdd(i)); } }
结果:
Question: 4 is odd ? Answer: false
分析:
结果竟然说4不是偶数?
取模运算当返回值为0时说明被整除
所以 偶数 % 2 = 0
取模运算当返回值非零时,它与左操作数具有相同的正负符号
所以 正奇数 % 2 = 1
负奇数 % 2 = -1
所以通过取模运算判断奇数时可以改成用 i % 2 != 0 来判断.
现在换一种思路来思考,所有的奇数的二进制最后一位必然为1,偶数的为0.
所以我们用1和参数进行按位与运算时,参数为奇数时与运算的结果为1,参数为偶数时与运算的结果为0
例如: 4 & 1 7 & 1
0100 0111
&0001 &0001
结果: 0000(0) 0001(1)
解决方案代码:
public class Oddity { public static boolean isOdd(int i){ return (i & 1) == 0; } public static void main(String[] args) { int i = 4; System.out.println("Question: " + i + " is odd ? "); System.out.println("Answer: " + isOdd(i)); } }
结果:
Question: 4 is odd ? Answer: true