• 0342. Power of Four (E)


    Power of Four (E)

    题目

    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?


    题意

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

    思路

    1. 循环判断余数;

    2. 直接求对数再进行判断;

    3. 找规律:

      首先,(4^{k+1})相当于将(4^k)的二进制向左移动两位,初始从1开始,所以4的幂次方的二进制表示中一定只有一个1;

      其次,因为每次向左移动两位,这个1后面一定跟着偶数个0,1一定出现在从右向左第奇数个位置上,只要将num和((0101)_2)相与,只要结果不为0,那么这个1一定出现在奇数为上。


    代码实现

    Java

    循环

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

    对数

    class Solution {
        public boolean isPowerOfFour(int num) {
            double n = Math.log(num) / Math.log(4);
            return n == ((int) n) * 1.0;
        }
    }
    

    找规律

    class Solution {
        public boolean isPowerOfFour(int num) {
            return ((num & (num - 1)) == 0) && ((num & 0x55555555) != 0);
        }
    }
    
  • 相关阅读:
    TCP通信 -C/S中的Socket与ServerSocket
    打印流 -可将数据写入文件/可改变输出方向
    转换流 -解决输入输出时编码格式不统一的问题
    字节/字符缓冲流
    Properties -IO相关的双列集合类
    IO流 -字符输入输出流,以及异常处理方法
    IO流
    线程间的通信
    o(* ̄︶ ̄*)o
    1
  • 原文地址:https://www.cnblogs.com/mapoos/p/13438742.html
Copyright © 2020-2023  润新知