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;
        }
    }
  • 相关阅读:
    转载一篇 Linux 命令总结
    Linux 常用命令学习
    frp 使用
    Anaconda使用记录
    Linux 学习
    lnmp下django学习
    lnmp安装学习
    学习DHT内容
    pyqt5配置
    MyBatisPlus 常用知识点总结
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11400716.html
Copyright © 2011-2022 走看看