leetcode 231. Power of Two(2的次方)

来源:互联网 发布:与樱井知香合作的男优 编辑:程序博客网 时间:2024/06/14 09:06

问题描述:

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

  首先,考虑最简单的做法,不断的除以2去进行验证,代码如下:

class Solution {    public boolean isPowerOfTwo(int n) {        if(n == 0) return false;        while(n != 1){            if(n % 2 != 0)                return false;            n /= 2;        }        return true;            }}

  然后,前一个题判断3的次方Power of Three要求不能用循环,那2的次方不用循环改怎么做呢?考虑到2的次方的特殊性,所有2的次方的数的二进制表示中,只有一位为“1”,所以利用n&(n-1)判断即可。代码如下:

class Solution {    public boolean isPowerOfTwo(int n) {        if(n <= 0) return false;        return ((n&(n-1)) == 0);         }}

  注意:&的优先级低于==,所以要加括号()。