首页 > 其他 > 详细

[LintCode] O(1) Check Power of 2

时间:2017-11-12 10:54:19      阅读:218      评论:0      收藏:0      [点我收藏+]

Using O(1) time to check whether an integer n is a power of 2.

Example

For n=4, return true;

For n=5, return false;

Challenge 

O(1) time

 

Solution 1.

 1 class Solution {
 2     public boolean checkPowerOf2(int n) {
 3         if(n <= 0) {
 4             return false;
 5         }
 6         while(n != 1) {
 7             if(n % 2 != 0) {
 8                 return false;
 9             }
10             n = n / 2;
11         }
12         return true;
13     }
14 }

 

Solution 2.  Bitwise operation

If n is a power of 2, then n‘s binary representation must have and only have one 1. So this problem is equivalent with Count 1 in Binary.

 1 class Solution {
 2     public boolean checkPowerOf2(int n) {
 3         if(n <= 0){
 4             return false;
 5         }
 6         int cnt = 0;
 7         while(n != 0){
 8             if((n & 1) == 1){
 9                 cnt++;
10                 if(cnt > 1){
11                     return false;
12                 }
13             }
14             n = n >>> 1;
15         }
16         return true;
17     }
18 }

 

Related Problems 

Count 1 in Binary

[LintCode] O(1) Check Power of 2

原文:http://www.cnblogs.com/lz87/p/7820945.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!