Using O(1) time to check whether an integer n is a power of 2.ExampleFor n=4, return trueFor n=5, return falseChallengeO(1) timeTags Expand
這道題考察bit manipulation. 1的個(gè)數(shù)只能有1個(gè)才是power of 2. 主要是要注意Integer.MIN_VALUE,這個(gè)只有一個(gè)1,但是是false
 1 class Solution { 2     /* 3      * @param n: An integer 4      * @return: True or false 5      */ 6     public boolean checkPowerOf2(int n) { 7         // write your code here 8         boolean one = false; 9         for (int i=0; i<31; i++) {10             if ((n>>>i & 1) == 0) continue;11             else if (!one) one = true;12             else return false;13         }14         if (one) return true;15         else return false;16     }17 };新聞熱點(diǎn)
疑難解答
圖片精選