• LeetCode 342. Power of Four (4的次方)


    Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

    Example:
    Given num = 16, return true. Given num = 5, return false.

    Follow up: Could you solve it without loops/recursion?


    题目标签:Bit Manipulation

      这道题目让我们判断一个数字是不是4的次方数,首先排除负数和0。然后利用2的次方数特性,如果 num & (num-1) == 0 的话,那么这个数字是2的次方数 (基于2进制原理)。利用这一点,排除所有不是2的次方数。最后,如果一个数字是4的次方数,那么这个数字 -1 一定可以被3整除。排除掉数字 -1不能被3整除的,剩下的就是4的次方数

    Java Solution:

    Runtime beats 24.44% 

    完成日期:06/26/2017

    关键词:Bit Manipulation

    关键点:基于 num & (num-1) 来判断是不是2的次方数

     1 public class Solution 
     2 {
     3     public boolean isPowerOfFour(int num) 
     4     {
     5         if(num <= 0) // if num is 0 or negative number
     6             return false;
     7         
     8         if((num & (num - 1)) != 0) // if num is not the power of 2
     9             return false;
    10         
    11         if((num - 1) % 3 != 0) // if num - 1 cannot be divided by 3 
    12             return false;
    13         
    14         return true;
    15     }
    16 }

    参考资料:

    http://www.cnblogs.com/grandyang/p/5403783.html

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    Scala--基础
    maven
    Storm 运行例子
    Storm 安装部署
    Storm
    Kafka 集群部署
    Redis Twemproxy
    Redis Sentinel
    获取URL中参数的值
    浏览器滚动条样式
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7082982.html
Copyright © 2020-2023  润新知