LeetCode 231. Power of Two

来源:互联网 发布:淘宝发错货的处理规定 编辑:程序博客网 时间:2024/06/14 08:48

Given an integer, write a function to determine if it is a power of two.

解法一:

class Solution {public:    bool isPowerOfTwo(int n) {        double res = log10(n) / log10(2);        if((res - (int)res) == 0) return true;        return false;    }};


后来遇到Power of four,发现了另一种解法,回来补上。一个数如果是power of two,那么num二进制最高位是,1,其余为0,(num - 1)最高位是0,其余是1,所以(num & num - 1)是0;

解法二:

class Solution {public:    bool isPowerOfTwo(int n) {        return (n > 0) && !(n & (n - 1));    }};


0 0