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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容