Leetcode: Power of Two

本文介绍了一种高效的方法来确定一个整数是否为2的幂次。通过位操作实现,不仅讨论了基本的实现逻辑,还特别注意到了特殊情况的处理,例如负数和Integer.MIN_VALUE的情况。
Given an integer, write a function to determine if it is a power of two.

Best Solution

1 class Solution {
2 public:
3     bool isPowerOfTwo(int n) {
4         if(n<=0) return false;
5         return !(n&(n-1));
6     }
7 };
1 public class Solution {
2     public boolean isPowerOfTwo(int n) {
3         return n>0 && Integer.bitCount(n) == 1;
4     }
5 }

 

 

还是有一个地方不小心:Integer.MIN_VALUE, 应该是false,但是因为只有一个1,我曾经判断为true。事实上,所有negative value都应该是false

 一旦符号位为1,就return false, 检查其他位只有1个1

 1 public class Solution {
 2     public boolean isPowerOfTwo(int n) {
 3         boolean flag = false;
 4         for (int i=0; i<=30; i++) {
 5             if (((n>>>i) & 1) == 1) {
 6                 if (!flag) flag = true;
 7                 else return false;
 8             }
 9         }
10         if (((n>>>31) & 1) == 1) return false;
11         return flag;
12     }
13 }

 

 做的时候遇到很多语法错误:

1. “==” 优先级 比 “&” 高, “&”表达式一定要括起来

2. >>是带符号的右移,如果是负数,高位始终补1. >>>才是无符号的右移

这样也可以,先确认除开符号位的31位只有一个1,然后确认符号位不为1,注意一定要无符号右移,或者写成 ((n>>31)&1) != 1

更好的方法:单独考虑符号位,一旦为1,return false

 1 public class Solution {
 2     public boolean isPowerOfTwo(int n) {
 3         boolean one = false;
 4         for (int i=0; i<31; i++) {
 5             if (((n>>i) & 1) == 1) {
 6                 if (!one) 
 7                     one=true;
 8                 else return false; 
 9             }
10         }
11         return one && (n>>>31)!=1; 
12     }
13 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值