231. Power of Two

来源:互联网 发布:淘宝客推广专区在哪里 编辑:程序博客网 时间:2024/05/29 04:13

题目来源【Leetcode】

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

判断一个数是否为2的N次方

方法一:取对数

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

方法二:用二进制的特点

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

方法三:用最大的2进制数

class Solution {public:    bool isPowerOfTwo(int n) {      return n > 0 && 4294967296%n == 0;    }};
原创粉丝点击