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 1:

    Input: 16
    Output: true
    

    Example 2:

    Input: 5
    Output: false

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

     

    M1: loop

    time = O(log_4(n)), space = O(1)

    class Solution {
        public boolean isPowerOfFour(int num) {
            if(num < 1) {
                return false;
            }
            while(num % 4 == 0) {
                num /= 4;
            }
            return num == 1;
        }
    }

    M2: 换底公式

    time = unknown, space = O(1)

    class Solution {
        public boolean isPowerOfFour(int num) {
            return (Math.log10(num) / Math.log10(4)) % 1 == 0;
        }
    }

    M3: bit manipulation

    n > 0 and (num & (num - 1)) == 0 makes sure num is a power of 2

    0x55555555 == 1010101010101010101010101010101 in binary with a length of 32,  (num & 0x55555555) != 0 makes sure the 1 locates in the odd location

    time = O(1), space = O(1)

    class Solution {
        public boolean isPowerOfFour(int num) {
            return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0;
        }
    }
  • 相关阅读:
    jpa入门案例----使用jpa对数据库进行查询、删除、修改操作
    ssm详细流程和步骤
    Dubbo
    ssm运行BUG
    mybatis 入门
    Linux
    Redis
    maven
    三层架构 开发模式
    转发和重定向的区别
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11400716.html
Copyright © 2011-2022 走看看