342. Power of Four

来源:互联网 发布:c语言游戏源代码 编辑:程序博客网 时间:2024/06/06 13:28

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的次幂


思路:一开始没看到下面的要求是尽量不用循环和递归,于是用循环写了一个,很简单,一直除4,知道最后值为1,则为true, 否则为false

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