[leetcode] 231. Power of Two
来源:互联网 发布:数据研究中心美国大学 编辑:程序博客网 时间:2024/06/15 12:54
题目
Given an integer, write a function to determine if it is a power of two.
判断一个数是否是2的次方数
解法一:如果一个数是2的幂,则除以2肯定能整除,最后商为1
public boolean isPowerOfTwo(int n){if(n<=0)return false;while(n%2==0){n=n/2;}return n==1;}
解法二:对于这种玩数字的题,我们应该首先考虑位操作 Bit Operation.
那么我们来观察下2的次方数的二进制写法的特点:
1 2 4 8 16 ....
1 10 100 1000 10000 ....
那么我们很容易看出来2的次方数都只有一个1,剩下的都是0,所以我们的解题思路就有了,我们只要每次判断最低位是否为1,然后向右移位,最后统计1的个数即可判断是否是2的次方数,
<< 左移位符号。num<<1 左移一位,相当于num乘以2
>>左移位符号。num>>1 左移一位,相当于num除以2
public boolean isPowerOfTwo2(int n){if(n<=0)return false;int result=0;while(n!=0){result+=n&1;n=n>>1;}return result==1;}
解法三:位操作,如果一个数是2的幂,其2进制表示最高位为1,则(n&(n-1))==0
public boolean isPowerOfTwo(int n){if(n<=0)return false;return (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
- 231. Power of Two LeetCode
- [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-231. Power of Two
- #leetcode#231. Power of Two
- 231.[Leetcode]Power of Two
- Leetcode 231. Power of Two
- hpuoj 【1287】数组最值 【水题】
- 爬去杭电hdu做题情况
- C# WPF 实现鼠标固定在指定范围内运动
- jQuery EasyUI中的Layout布局(二)
- CS231n课程笔记翻译8:神经网络笔记 part3
- [leetcode] 231. Power of Two
- 剑指offer题65
- fastText原理及应用
- #2017 Multi-University Training Contest
- 矩阵中的路径—递归
- 如何向一个Fragment传递参数---setArguments方法的介绍
- 网页打开本地应用程序
- Java学习之ArrayList和LinkedList
- cartographer源码分析(21)-sensor-ordered_multi_queue.h