Leetcode--231、Power of Two
来源:互联网 发布:微信淘宝推广怎么做的 编辑:程序博客网 时间:2024/05/29 08:45
题目
Given an integer, write a function to determine if it is a power of two.
思路
如果是2的幂,则二进制的所有位中,有且仅有一个1。
可以复用 “Number of 1 Bits” 中的函数,计算出1的个数,如果为1,则返回true, 不为1,返回 false。
还有更巧妙的办法。如果一个数是2的幂,则它的二进制最高位必然为1,其余为0,此时如果我们减1的话,最高位降为0,其余位变为1,如果把两个数按位与,结果必然为0。
代码
class Solution {public: bool isPowerOfTwo(int n) { return (n>0) && ((n&(n-1)) == 0); }};
阅读全文
0 0
- leetcode-231 Power of Two
- leetcode 231:Power of Two
- LeetCode 231: Power of Two
- leetcode 231: Power of Two
- leetcode[231]:Power of Two
- Power of Two(leetcode 231)
- leetcode-231-Power of Two
- LeetCode 231 Power of Two
- leetCode #231 Power of Two
- leetcode 231: Power of Two
- [Leetcode]#231 Power of Two
- Leetcode #231 Power of Two
- [LeetCode 231] Power of Two
- [leetcode 231]Power of Two
- 【LeetCode】231Power of Two
- 【LeetCode】231Power of Two
- LeetCode 231 Power of Two
- LeetCode 231:Power of Two
- 【Linux】模拟实现sleep函数
- 远程主机强迫关闭了一个现有的连接
- Innodb中的事务隔离级别和锁的关系
- mybatis 开发中遇到的问题(一)
- react-表单
- Leetcode--231、Power of Two
- H5制作饼状图
- linux 内核学习----------模块(LKM:loading kernel module)
- Kotlin学习笔记——标准库kotlin.io / java.io.File
- Activity状态保存
- 33 linux服务管理
- MongoDB和Redis区别
- Android 官方兼容库 EmojiCompat Support Library
- Linux线程学习总结