leetcode之Power of Two
来源:互联网 发布:拉货搬家软件 编辑:程序博客网 时间:2024/06/01 10:37
判断是不是2的幂次,有好几种方法,比如以二为底取log,比如依次除以二看能不能除到结果为1为止,比如n&(n-1)==0。
(1)C语言实现
bool isPowerOfTwo(int n) {
if(n>0 && (n&(n-1)==0))
return true;
else
return false;
}
/*解法二
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
while(n%2==0){
n /= 2;
}
return n==1;
}*/
(2)C++实现
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
double n1 = log10(n)/log10(2);
return (n1-(int)n1)==0;
}
};
/*解法二
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
while(n%2==0){
n /=2;
}
return n==1;
}
};
*/
/*解法三
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
return (n&(n-1))==0;
}
};
*/
(3)java实现
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n>0 && (n&(n-1)==0))
return true;
else
return false;
}
}
- LeetCode之Power of Two
- leetcode 之 power of two
- leetcode之Power of Two
- leetcode之Power of Two
- LeetCode之Power of Two
- [LeetCode] Power of Two
- 【LeetCode】Power of Two
- [Leetcode]Power of Two
- [leetCode] Power of Two
- leetcode --Power of Two
- leetcode: Power of Two
- LeetCode Power of Two
- [LeetCode] Power of Two
- LeetCode Power of Two
- [leetcode] Power of Two
- [Leetcode]Power of Two
- Leetcode: Power of Two
- [LeetCode]Power of Two
- LeetCode:计算相同数组元素的下标差(Contains Duplicate II)
- HDFS的备份机制
- ACM常用的C++头文件!
- 基于AVPlayer 自定义播放器
- HTML学习笔记(十四)URL
- leetcode之Power of Two
- 1003. Emergency
- 我的linux学习之路:Git常用命令
- 蓝桥杯单片机设计与开发笔记(四)
- Codeforces Round #346 (Div. 2) ABCDE
- POJ 2114 Boatherds 点分治
- Java集合---ConcurrentHashMap原理分析
- IOSRadioGroup
- 数据结构之“堆”