[leetcode]-231. Power of Two(C语言)
2018-03-17 19:40
387 查看
Given an integer, write a function to determine if it is a power of two.
方法一:bool isPowerOfTwo(int n) {
if(n<0)
return false;
double s=log10(n)/log10(2);
if(s-(int)s==0)
return true;
return false;
}方法二:bool isPowerOfTwo(int n) {
int i,j;
if(n<=0)
return false;
if(n==1)
return true;
while(n!=1)
{
if(n%2==0)
n=n/2;
else
return false;
}
return true;
}方法三:
将整数n转换为二进制形式,那么2的幂次为10,100,1000,等的形式,将转换后的二进制放在数组里,看是否每一位都是0即可(开头的1没必要存储下来)
bool isPowerOfTwo(int n) {
int a,b,i,c=0;
int s[100];
if(n<=0)
return false;
if(n==1)
return true;
a=n/2;
while(a!=0)
{
b=n%2;
s[c++]=b;
n=a;
a=n/2;
}
for(i=0;i<=c-1;i++)
{
if(s[i]!=0)
break;
}
if(i==c)
return true;
return false;
}
方法一:bool isPowerOfTwo(int n) {
if(n<0)
return false;
double s=log10(n)/log10(2);
if(s-(int)s==0)
return true;
return false;
}方法二:bool isPowerOfTwo(int n) {
int i,j;
if(n<=0)
return false;
if(n==1)
return true;
while(n!=1)
{
if(n%2==0)
n=n/2;
else
return false;
}
return true;
}方法三:
将整数n转换为二进制形式,那么2的幂次为10,100,1000,等的形式,将转换后的二进制放在数组里,看是否每一位都是0即可(开头的1没必要存储下来)
bool isPowerOfTwo(int n) {
int a,b,i,c=0;
int s[100];
if(n<=0)
return false;
if(n==1)
return true;
a=n/2;
while(a!=0)
{
b=n%2;
s[c++]=b;
n=a;
a=n/2;
}
for(i=0;i<=c-1;i++)
{
if(s[i]!=0)
break;
}
if(i==c)
return true;
return false;
}
相关文章推荐
- Leetcode 231. Power of Two & 326. Power of Three & 342. Power of Four
- [Leetcode] 231. Power of Two 解题报告
- 【LeetCode】231. Power of Two
- LeetCode(九)231. Power of Two&405. Convert a Number to Hexadecimal
- leetcode - 231. Power of Two
- LeetCode-1-Two Sum(C语言实现)
- Leetcode 231. Power of Two (Easy) (cpp)
- [C语言][LeetCode][167]Two Sum II - Input array is sorted
- LeetCode-2-Add Two Nuns(C语言实现)
- leetcode 21. Merge Two Sorted Lists(C语言,合并两个排序的链表为一个排序链表)32
- 【一天一道LeetCode】#231. Power of Two
- [C语言][LeetCode][2]Add Two Numbers
- Leetcode 231. Power of Two
- LeetCode_Easy心得:21. Merge Two Sorted Lists(C语言)
- leetcode 231. Power of Two(2的次方)
- LeetCode 231. Power of Two 解题报告
- leetcode 231. Power of Two
- LeetCode 231. Power of Two (算法,计算二进制数中1的位数)
- LeetCode 231. Power of Two
- leetcode 617. Merge Two Binary Trees(C语言,二叉树求和,递归)53