前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:342. Power of Four

LeetCode笔记:342. Power of Four

作者头像
Cloudox
发布2021-11-23 15:31:04
2180
发布2021-11-23 15:31:04
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

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?

大意:

给出一个数字(有符号32位),写一个函数来检查它是不是4的次方数。 例子: 给出 num = 16,返回true。给出 num = 15,返回false。 进阶:你能不能不用循环或者递归来解决它。

思路:

这道题也是老题目了,既可以用判断2的次方数的方法稍作修改,即转化为二进制数后判断1后面的0个数是不是双数。也可以直接用判断3的次方数的方法来做,直接求对数。

代码1(Java):

代码语言:javascript
复制
public class Solution {
    public boolean isPowerOfFour(int num) {
        // 转化为二进制数来判断
        if (num < 0) return false;
        String binaryStr = Integer.toBinaryString(num);
        for (int i = 0; i < binaryStr.length(); i++) {
            if (i == 0 && binaryStr.charAt(i) !='1') return false;
            else if (i > 0 && binaryStr.charAt(i) != '0') return false;
        }
        if (binaryStr.length() % 2 != 1) return false;
        return true;
    }
}

代码2(Java):

代码语言:javascript
复制
public class Solution {
    public boolean isPowerOfFour(int num) {
        // 求对数
        return (num > 0 && (Math.log10(num) / Math.log10(4)) % 1 == 0);
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码1(Java):
  • 代码2(Java):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档