[LeetCode] 342. Power of Four(位操作)
传送门
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(位操作)相关推荐
- [leetcode] 342. Power of Four
题目 Given an integer (signed 32 bits), write a function to check whether it is a power of 4.Example: ...
- 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 ...
- [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: ...
- 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: ...
- LeetCode:326. Power of Three
2019独角兽企业重金招聘Python工程师标准>>> Given an integer, write a function to determine if it is a powe ...
- leetcode 231. Power of Two
Given an integer, write a function to determine if it is a power of two. class Solution(object):def ...
- 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 ...
- LeetCode之Power of Two
1.题目 Given an integer, write a function to determine if it is a power of two. Credits: Special thank ...
- LeetCode 342. 4的幂(位运算)
文章目录 1. 题目 2. 解题 2.1 通用解法 2.2 找规律 1. 题目 给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方. 示例 1: 输入: 16 输出: t ...
最新文章
- matlab mlpkginstall,Matlab选择mingw编译器
- IBatis初体验2
- Android跨进程通信二——AIDL
- Redis简介及入门
- python_类方法和静态方法
- 深度召回算法在字节跳动推荐系统的应用实践
- command shortcut paste
- Kubernetes学习指南,轻松拥抱云原生
- Mysql几种索引类型的区别及适用情况
- LayaAir UI 组件 # HSlider,VSlider(水平/垂直滑动条)
- discuz 任务扩展
- 方法重写与方法重载的区别
- LaTeX 插入章节和目录
- 支付宝信用贷豪掷38亿抢客,微粒贷不怂
- 联想Z5 Pro划时代旗舰发布 屏占比95.06%售价1998元起
- 人工智能产业盛宴:2019 AIIA开发者大会即将揭幕
- SpringAop篇 (1) AOP 基础之动态代理的实现
- 带你入门多目标跟踪(四)外观模型 Appearance Model
- Flutter(十六)——Hero动画
- 谷歌程序员年薪高达25万美元以上