Lintcode: O(1) Check Power of 2
生活随笔
收集整理的這篇文章主要介紹了
Lintcode: O(1) Check Power of 2
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Using O(1) time to check whether an integer n is a power of 2.
Example
For n=4, return trueFor n=5, return falseChallenge
O(1) timeTags Expand
這道題考察bit manipulation. 1的個數只能有1個才是power of 2. 主要是要注意Integer.MIN_VALUE,這個只有一個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 };?
轉載于:https://www.cnblogs.com/EdwardLiu/p/4385821.html
總結
以上是生活随笔為你收集整理的Lintcode: O(1) Check Power of 2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最长子串(FZU2128)
- 下一篇: mustache,用{{}}获取值