判断是否为奇数的有趣算法

题目描述

写一个程序,判断是否为奇数。很简单的题目,但是实现可以有很多种,也很有意思。

思考

最简单的是这样的

1
2
3
4
5
6
7
public static boolean (int i) {
if (i % 2 == 1) {
return true;
} else {
return false;
}
}

我们进一步观察,发现这一句i % 2 == 1是boolean类型,那么可以优化成这样

1
2
3
public static boolean (int i) {
return i % 2 == 1;
}

但是发现没有考虑负数的问题,于是再次修改

1
2
3
public static boolean (int i) {
大专栏  判断是否为奇数的有趣算法="line"> return i % 2 == 1 || i % 2 == -1;
}

仔细观察,再次优化

1
2
3
public static boolean (int i) {
return i % 2 != 0;
}

一般面试写到这里就足够了。

然而,并没有这么简单。

朋友,你知道二进制吗?

移位运算符是比取模速度快的,再次改

1
2
3
public static boolean (int i) {
return i >> 1 << 1 != i;
}

这个比较厉害,大部分人想不到这里,然而。。。

1
2
3
public static boolean isOdd(int i) {
return (i & 1) == 1;
}

& 都为1则为1,其它为0

逼格满分。
掌声。

原文地址:https://www.cnblogs.com/lijianming180/p/12255804.html