首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Leetcode_342_Power of Four

Leetcode_342_Power of Four

作者头像
bear_fish
发布2018-09-19 11:50:31
发布2018-09-19 11:50:31
3460
举报

http://blog.csdn.net/pistolove/article/details/52198328

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?  Credits:  Special thanks to @yukuairoy for adding this problem and creating all test cases.  Subscribe to see which companies asked this question 


思路:

(1)该题为给定一个整数,判断该整数是否为4的次方数。

(2)该题属于简单题。用一个循环进行判断即可得到结果。由于用循环比较简单,这里不再累赘。下文简单阐述两种非循环的实现方式,都是基于2的次方数实现的,感兴趣可以看看。

(3)算法代码实现如下,希望对你有所帮助。


代码语言:java
复制
package leetcode;

public class Power_of_Four {

    public static boolean isPowerOfFour(int num) {
        if (num <= 0)
            return false;

        if (num == 1)
            return true;

        while (true) {
            if (num % 4 == 0) {
                num = num / 4;
                if (num == 1)
                    return true;
            } else {
                return false;
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

网上的一些其它算法实现:

(1)如果该整数是2的次方数,只要是4的次方数,减1之后可以被3整除,则说明该整数是4的次方数,见下方代码:

代码语言:c#
复制
public class Solution {
    public boolean isPowerOfFour(int num) {
        return num > 0 && ((num & (num - 1))==0) && ((num - 1) % 3 == 0);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

(2)2的次方数在二进制下只有最高位是1,但不一定是4的次方数,观察发现4的次方数的最高位的1都是计数位,只需与上0x55555555(等价 1010101010101010101010101010101),如果得到的数还是其本身,则可以肯定其为4的次方数,见下方代码:

代码语言:c#
复制
public class Solution {
    public boolean isPowerOfFour(int num) {
        return num > 0 && ((num & (num - 1))==0) &&  (num & 0x55555555) == num;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年06月25日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档