LeetCode 231. Power of Two(2的N次幂)

来源:互联网 发布:北京致远软件 编辑:程序博客网 时间:2024/06/05 03:34

原题网址:https://leetcode.com/problems/power-of-two/

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

思路:数字n是2的整数次幂,当且仅当n的二进制表示有且只有一个1。

方法一:直接统计1比特数。

public class Solution {    public boolean isPowerOfTwo(int n) {        int count = 0;        for(;n>0 && count<=1; count += (n&1), n>>=1);        return count == 1;    }}

方法二:直接获取最低位1比特。

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

0 0