public boolean isOdd(int i)
根据上面定义写出一个判断参数是否为奇数的方法。
初学者:
public boolean isOdd(int i) {
if (i % 2 == 1) {
System.out.println("i是奇数");
} else {
System.out.println("i是偶数");
}
}
刚参加工作:
public boolean isOdd(int i) {
if (i % 2 == 1) {
return true;
} else {
return false;
}
}
工作半年:
public boolean isOdd(int i) {
return i % 2 == 1;
}
工作一年:
public boolean isOdd(int i) {
return i % 2 == 1 || i % 2 == -1;
}
工作一年半:
public boolean isOdd(int i) {
return i % 2 != 0;
}
工作两年:
public boolean isOdd(int i) {
return i << 1 >> 1 != i;
}
工作两年半:
public boolean isOdd(int i) {
return (i & 1) == 1;
}
大家在哪个层次呢?欢迎留言!
总结:在写代码的过程中,还是要思考底层是怎么运行这段代码的。拿上面写的代码举例,从一开始时返回true和false,到直接返回布尔表达式,再到位运算,运行效率上是会越来越好的。因为底层做的事情越来越少,越来越符合计算机的运算逻辑,所以只有了解原理,才能写出简洁高效的代码。