zoukankan      html  css  js  c++  java
  • [LintCode] O(1) Check Power of 2

    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

  • 相关阅读:
    2.17-2.23第一周总结
    10号总结
    9日总结
    8号总结
    7号寒假总结
    6号
    读后感《程序员的修炼之道:从小工到专家》1
    java第二次动手动脑
    回文判断
    二进制的原码,反码以及补码介绍
  • 原文地址:https://www.cnblogs.com/lz87/p/7820945.html
Copyright © 2011-2022 走看看