public static boolean isOdd(int i){
return i%2 == 1;
}
Solution:
以上程序只有3/4的数正确,因为当i是负数时,不管是奇数还是偶数都会返回false;
java puzzlers 上的提示:
test that your methods behave properly when passed negative, zero, and postive values for each numerical parameter.
较好方案:
public static boolean isOdd(int i){
return i%2 != 0;
}
或
pbulic static boolean isOdd(int i){
reutrn(i & 1) != 0;
}
return i%2 == 1;
}
Solution:
以上程序只有3/4的数正确,因为当i是负数时,不管是奇数还是偶数都会返回false;
java puzzlers 上的提示:
test that your methods behave properly when passed negative, zero, and postive values for each numerical parameter.
较好方案:
public static boolean isOdd(int i){
return i%2 != 0;
}
或
pbulic static boolean isOdd(int i){
reutrn(i & 1) != 0;
}