231. Power of Two

来源:互联网 发布:金数据登录 编辑:程序博客网 时间:2024/05/18 17:03

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

My solution:

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

Or use Integer.bitCount.
public class Solution {    public boolean isPowerOfTwo(int n) {        return n>0&&Integer.bitCount(n)==1;            }}

0 0
原创粉丝点击