传送门

Description

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其余都是0,并且可以发现规律,从4的零次幂开始列举,可以发现与上一个幂次相比,隔了一个0,也就是将4的幂次的二进制位写在一起,呈现出...0101...的形式,因此根据  num & (num - 1)可以判定二进制位是否只有一个1,然后再与十六进制的55555555相与即可判断是否有4的幂次的表现形式,因为十六进制的5的表现形式正好是0101。

class Solution {
public://3msbool isPowerOfFour(int num) {return !(num & (num - 1)) && (num & 0x55555555);}
};

  

转载于:https://www.cnblogs.com/ZhaoxiCheung/p/7400404.html

[LeetCode] 342. Power of Four(位操作)相关推荐

  1. [leetcode] 342. Power of Four

    题目 Given an integer (signed 32 bits), write a function to check whether it is a power of 4.Example: ...

  2. leetcode 342. Power of Four

    Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Gi ...

  3. [LeetCode][JavaScript]Power of Three

    Power of Three Given an integer, write a function to determine if it is a power of three. Follow up: ...

  4. leetcode 231. Power of Two 判断是否为2的幂 Java

    231. Power of Two Given an integer, write a function to determine if it is a power of two. Credits: ...

  5. LeetCode:326. Power of Three

    2019独角兽企业重金招聘Python工程师标准>>> Given an integer, write a function to determine if it is a powe ...

  6. leetcode 231. Power of Two

    Given an integer, write a function to determine if it is a power of two. class Solution(object):def ...

  7. LeetCode - 231. Power of Two

    Given an integer, write a function to determine if it is a power of two. Example 1: Input: 16 Output ...

  8. LeetCode之Power of Two

    1.题目 Given an integer, write a function to determine if it is a power of two. Credits: Special thank ...

  9. LeetCode 342. 4的幂(位运算)

    文章目录 1. 题目 2. 解题 2.1 通用解法 2.2 找规律 1. 题目 给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方. 示例 1: 输入: 16 输出: t ...

最新文章

  1. matlab mlpkginstall,Matlab选择mingw编译器
  2. IBatis初体验2
  3. Android跨进程通信二——AIDL
  4. Redis简介及入门
  5. python_类方法和静态方法
  6. 深度召回算法在字节跳动推荐系统的应用实践
  7. command shortcut paste
  8. Kubernetes学习指南,轻松拥抱云原生
  9. Mysql几种索引类型的区别及适用情况
  10. LayaAir UI 组件 # HSlider,VSlider(水平/垂直滑动条)
  11. discuz 任务扩展
  12. 方法重写与方法重载的区别
  13. LaTeX 插入章节和目录
  14. 支付宝信用贷豪掷38亿抢客,微粒贷不怂
  15. 联想Z5 Pro划时代旗舰发布 屏占比95.06%售价1998元起
  16. 人工智能产业盛宴:2019 AIIA开发者大会即将揭幕
  17. SpringAop篇 (1) AOP 基础之动态代理的实现
  18. 带你入门多目标跟踪(四)外观模型 Appearance Model
  19. Flutter(十六)——Hero动画
  20. 谷歌程序员年薪高达25万美元以上

热门文章

  1. Python入门--闭包,工程函数
  2. cactiez v11使用配置mysql_cactiez应用监控部署手册.doc
  3. 电商网站模板_微购物商城网站建设:要做好这6点!
  4. 如何计算页面打开获取流量_网站SEO优化如何获取更多的流量?
  5. 5319. 删除回文子序列
  6. 栈的链式存储框架搭建
  7. docker使用填坑记录(修改无法启动容器, 拉取国外镜像)
  8. BIOS和DOS中断例程的安装过程
  9. 贺利坚老师汇编课程21笔记:用汇编语言写的源程序
  10. hdu 1176 免费馅饼(nyist 613)