342. 4的幂(java)

给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。

示例 1:

输入: 16
输出: true
示例 2:

输入: 5
输出: false
进阶:
你能不使用循环或者递归来完成本题吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/power-of-four
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
    public boolean isPowerOfFour(int num) {
        int n;
        if(num == 1) return true;
        else if(Math.sqrt(num)%2==0) n = (int)Math.sqrt(num);
        else return false;
        return isPowerOfTwo(n);
    }
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n&(n-1))==0;
    }
}
发布了99 篇原创文章 · 获赞 18 · 访问量 7052

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/103962683