231. Power of Two

来源:互联网 发布:傻大木 知乎 编辑:程序博客网 时间:2024/06/02 00:18

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

思路:

二的倍数首先必须大于0,其次最高位是1,其他都是0。可以循环遍历最后一位是否为1,然后计算1的个数,这里直接利用2的倍数-1之后除了最高位是0,其他全是1的特点。

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


0 0
原创粉丝点击