Leetcode - Power of Two

傻逼题目。不用多想。

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n <= 0)
            return false;
        boolean ret = false;
        for (int i = 0; i < 32; i++) {
            if ((n & 0x0001) == 1) {
                if (!ret)
                    ret = true;
                else {
                    ret = false;
                    break;
                }
            }
            n = (n >> 1);
        }
        return ret;
    }
}

**
总结: bit manipulation
刷了两道简单题,神清气爽!
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n < 0) {
            return false;
        }
        
        int c = 0;
        int base = 1;
        for (int i = 0; i < 32; i++) {
            if ((n & base) != 0) {
                c++;
                if (c > 1) {
                    return false;
                }
            }
            base <<= 1;
        }
        
        return c == 1;
    }
}

这道题目并不难。

Anyway, Good luck, Richardo! — 10/12/2016

My code:

public class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && Math.pow(2, (int) (Math.log(Integer.MAX_VALUE) / Math.log(2))) % n == 0;
    }
}

受 power of three 启发。

Anyway, Good luck, Richardo! — 10/14/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/7c170f2a5e0f#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞