今天寫了篇文章判斷一個數是否是2的N次方http://www.cnblogs.com/mybear/archive/2011/03/03/1969851.html
沒想到各位的熱情著麼高,呵呵,感謝每一位關注的朋友,本來也想寫篇關於回複中每個方法的介紹的,不過被undefined
朋友搶了先,各位可以參考他的兩篇文章
1)一名曾經的測試人員, 看大家貢獻的關於2的n次方的檢測的代碼
2)結果正確不代表思路正確
根據回複,我整理出了6個正確的方法,如下
#region Neeley http://www.cnblogs.com/mybear/public static bool Check1(int num){ int i = 1; while (true) { if (i > num) return false; if (i == num) return true; i = i * 2; }}public static bool Check2(int num){ if (num == 1) return true; else { do { if (num % 2 == 0) num = num / 2; else return false; } while (num != 1); return true; }}#endregion#region 執手淚眼 http://www.cnblogs.com/liszt/public static bool Check3(int num){ double result = Math.Log(num, 2); return result.ToString().IndexOf(".") < 0;}#endregion#region llzhzhb http://http://home.cnblogs.com/141189///x << (31 - i) >> 31 就 是取位元字中的第i+1位public static bool Check4(int num){ uint x =Convert.ToUInt32(num); bool y = false; for (int i = 0; i < 32; i++) { if (x << (31 - i) >> 31 == 1) if (!y) y = true; else { y = false; break; } } return y;}#endregion#region 西夏普躲耐特 http://www.cnblogs.com/hncjp1989/public static bool Check5(int num){ return ((num & (num - 1)) == 0) ? true : false;}#endregion#region lipan http://www.cnblogs.com/lipan/public static bool Check6(int num){ if (num == 1) return true; return Regex.IsMatch(Convert.ToString(num, 2), "^10+$");}#endregion
此六種方法從上到下一次是Check1----Check6,迴圈1到99999999次,開發環境VS2008+Window7,使用Release編譯,執行結果是:
從可以看到,最快當然還是x & (x - 1)
其次是我自己寫的一個do while迴圈,看來迴圈並不一定是最壞的方法
源碼如下,大家有自己的方法,也可以添加上來,比較下速度!
http://files.cnblogs.com/mybear/ConsoleApplication.rar