zoukankan      html  css  js  c++  java
  • LeetCode 231. Power of Two

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


    题目标签:Math; Bit Manipulation

      题目给了我们一个int n,让我们判断n 是不是 2的次方数。

      这一题不难,但是这里有一个比较巧妙的方法,利用bit manipulation。

      如果一个数字是 2的次方数,那么这个数字 肯定只有一个bit 是1。这样的话,利用 n & (n-1) 来判断,如果结果 == 0,那么这个n 是2的次方数。

      举例:

      n = 8  -  binary = 1 0 0 0

      n = 7  -  binary = 0 1 1 1

      8 & 7 = 0 0 0 0

    Java Solution:

    Runtime beats 25.01% 

    完成日期:06/16/2017

    关键词:Bit Manipulation

    关键点:一个数字 如果是 2的次方数,那么它只能有一个bit 是1; 利用 n & (n-1) == 0 来判断

     1 class Solution 
     2 {
     3     public boolean isPowerOfTwo(int n) 
     4     {
     5         if(n <= 0)
     6             return false;
     7         
     8         return ( (n & (n-1)) == 0 );    
     9     }
    10 }

    参考资料:https://discuss.leetcode.com/topic/18365/one-line-java-solution

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    结对作业
    黄金分割点(第五周 c语言版)
    小程序(第四周)
    读程序作业(第三周)
    vs2013的安装及测试(第三周)
    学习进度条(第6周)
    努力爬的蜗牛
    学习日记1
    团队作业(七)
    团队作业(六)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/8349418.html
Copyright © 2011-2022 走看看