# 菜鸟、普通、老鸟程序猿如何写奇数判断？--位操作符妙用

1. 菜鸟程序猿

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;
}
}

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 % 2!=0;//如果一个数是偶数，就算是负数整除2余数也为0
}
}

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，本质是取二进制的最后一位的值
}
}

【1】java解惑

posted on 2019-08-30 17:08  一天不进步，就是退步  阅读(494)  评论(4编辑  收藏