提到的.
1. 奇偶判断不要使用 i % 2 == 1 来判断是否是奇数,因为i为负奇数时不成立,请使用 i % 2 != 0 来判断是否是奇数,或使用 高效式 (i & 1) != 0来判断。
想着今天还用%2来判断,虽然传入的值不会出现负数,但难保以后不会掉坑里,所以留意了一下高效式.高效式,一点印象都没有.赶紧测试一下
(i & 1)
//两个只要有一个是偶数就为等于0
//两个都是奇数等于1
现在只用(||)(&&)
看了一下这个,都是转2进制再运算.测了一下,发现太麻烦了,还是别拿这个来装逼的好,万一自己也忘了就麻烦了.
System.out.println(13&17);//1
System.out.println(12&17);//0
System.out.println(17&12);//0
System.out.println(12&18);//0
System.out.println(-12&18);//16
System.out.println(-12&-18);//28
System.out.println(12&-18);//12
System.out.println(-3&-7);//-7
System.out.println(4|1);//5
System.out.println(13|1);//13
System.out.println(13|17);//29
System.out.println(12|17);//29
System.out.println(17|12);//29
System.out.println(12|18);//30
System.out.println(129&128);//128
System.out.println(129|128);//129
文章还说到使用位移操作(>>)(<
九、使用移位操作来代替'a / b'操作"/"是一个很“昂贵”的操作,使用移位操作将会更快更有效。例子:
public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a / 4; // should be replaced with "a >> 2".
int div2 = a / 8; // should be replaced with "a >> 3".
int temp = a / 3;
}
}
更正:
public class sdiv {
public static final int num = 16;
public void calculate(int a) {
int div = a >> 2;
int div2 = a >> 3;
int temp = a / 3; // 不能转换成位移操作
}
}
十、使用移位操作代替'a * b'同上。[i]但我个人认为,除非是在一个非常大的循环内,性能非常重要,而且你很清楚你自己在做什么,方可使用这种方法。否则提高性能所带来的程序晚读性的降低将是不合算的。例子:
public class smul {
public void calculate(int a) {
int mul = a * 4; // should be replaced with "a <
int mul2 = 8 * a; // should be replaced with "a <
int temp = a * 3;
}
}
更正:
package opt;
public class smul {
public void calculate(int a) {
int mul = a <
int mul2 = a <
int temp = a * 3; // 不能转换
}
}