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/

  • 相关阅读:
    app 后端技术
    别为大公司拼命
    ifconfig 工具
    route工具
    ping 和 traceroute 命令
    IP路由选择
    TCP的那些事儿(下)
    TCP的那些事儿(上)
    Openresty 与 Tengine
    Excel.Application SaveAs 把excel转换为html
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/8349418.html
Copyright © 2011-2022 走看看