算法系列——Power of Two

来源:互联网 发布:新闻资讯网站php源码 编辑:程序博客网 时间:2024/06/03 14:18

题目描述

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

解题思路

还是考察位操作。如果一个数n是2的幂,例如 4( 100)
4-1=3(011) ,减去一后会将原来高位1 后面的位全部补为1,4(100)&3(011)=0 ,进行与操作,结果为0.

程序实现

public class Solution {    public boolean isPowerOfTwo(int n) {        if(n<=0)            return false;        return ((n-1)&n)==0;    }}
原创粉丝点击