java簡單的判斷奇偶數方法(i & 1) != 0 i爲奇數

    今天找提高代碼性能的方法,剛好看到這篇文章裏http://www.cnblogs.com/chinafine/articles/1787118.html

提到的.

1. 奇偶判斷 
不要使用 i % 2 == 1 來判斷是否是奇數,因爲i爲負奇數時不成立,請使用 i % 2 != 0 來判斷是否是奇數,或使用 高效式 (i & 1) != 0來判斷。 

   想着今天還用%2來判斷,雖然傳入的值不會出現負數,但難保以後不會掉坑裏,所以留意了一下高效式.高效式,一點印象都沒有.趕緊測試一下

(i & 1)

//兩個只要有一個是偶數就爲等於0

//兩個都是奇數等於1

然後發現基本沒再用位運算符了與(&)、非(~)、或(|)、異或(^)

現在只用(||)(&&)

http://blog.csdn.net/vebasan/article/details/6193916

看了一下這個,都是轉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 << 2".
        int mul2 = 8 * a;         // should be replaced with "a << 3".
        int temp = a * 3;
    }
}



更正: 

package opt;
public class smul {
    public void calculate(int a) {
        int mul = a << 2;  
        int mul2 = a << 3;
        int temp = a * 3;       // 不能轉換
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章