您的位置 首页 java

菜鸟、一般、老鸟程序猿如何写奇数判断?java内幕之位操作符妙用

背景:

判断一个整数是否为奇数?

看一下程序猿都是怎么反应?

菜鸟程序猿

代码就是一个撸字:

public class TestOdd {
public static void main(String[] args) {
int oddNum=153;
System.out.println(isOdd(oddNum));
int evenNum=9284;
System.out.println(isOdd(evenNum));
}

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

没有问题,搞定!

一般程序猿

上面的代码一看就是菜鸟写的,都没有考虑int的取值范围,看老孙俺的!

public class TestOdd {
public static void main(String[] args) {
 /**
 * A constant holding the minimum value an {@code int} can
 *  have , -2<sup>31</sup>. 
 @Native public static final int MIN_VALUE = 0x80000000;
 * A constant holding the maximum value an {@code int} can
 * have, 2<sup>31</sup>-1. 
 @Native public static final int MAX_VALUE = 0x7fffffff;
 */int oddNum=Integer.MAX_VALUE;
System.out.println(isOdd(oddNum));
int evenNum=Integer.MIN_VALUE;
System.out.println(isOdd(evenNum));
}

public static boolean isOdd(int i){
return i % 2!=0;//如果一个数是偶数,就算是负数 整除 2余数也为0
}
}
 

老鸟程序猿

现在的年轻人都不懂的珍惜呀!%2 很浪费资源的,使用&比较省事。

public class TestOdd {
public static void main(String[] args) {
 /**
 * A constant holding the minimum value an {@code int} can
 * have, -2<sup>31</sup>. 
 @Native public static final int MIN_VALUE = 0x80000000;
 * A constant holding the maximum value an {@code int} can
 * have, 2<sup>31</sup>-1. 
 @Native public static final int MAX_VALUE = 0x7fffffff;
 */int oddNum=Integer.MAX_VALUE;
System.out.println(isOdd(oddNum));
int evenNum=Integer.MIN_VALUE;
System.out.println(isOdd(evenNum));
}

public static boolean isOdd(int i){
return (i & 1)!=0;//1的十六进制为0x00000001,本质是取 二进制 的最后一位的值
}
}
 

另外记住:除法的话,如是2的x次方的话,使用移位更快哦。

文章来源:智云一二三科技

文章标题:菜鸟、一般、老鸟程序猿如何写奇数判断?java内幕之位操作符妙用

文章地址:https://www.zhihuclub.com/188635.shtml

关于作者: 智云科技

热门文章

网站地图