zoukankan      html  css  js  c++  java
  • 342. Power of Four

    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?

    判断一个数是不是4的次方

    C++(6ms):

    1 class Solution {
    2 public:
    3     bool isPowerOfFour(int num) {
    4         return (num&(num-1))==0 && (num-1)%3==0 ;
    5     }
    6 };

    C++(9ms):

     1 class Solution {
     2 public:
     3     bool isPowerOfFour(int num) {
     4         if (num&(num-1))
     5             return false ;
     6         if (num < 0)
     7             return false ;    
     8         while(num){
     9             if (num&1)
    10                 return true ;
    11             num>>=2 ;
    12         }
    13         return false ;
    14     }
    15 };

    java(3ms):

    1 class Solution {
    2     public boolean isPowerOfFour(int num) {
    3         return (num&(num-1))==0 && (num-1)%3==0 ;
    4     }
    5 }
  • 相关阅读:
    linux 常用函数
    现在什么都不是浮云
    laosao
    2012年
    工作任务
    代码整理
    如何做一个男人
    很重要的2点
    录像预录的设计及实现
    弄了一个小网站
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7814730.html
Copyright © 2011-2022 走看看