leetcode-231-power-of-two

题目

Given an integer, write a function to determine if it is a power of two.

Example 1:

1
2
3
Input: 1
Output: true
Explanation: 20 = 1

Example 2:

1
2
3
Input: 16
Output: true
Explanation: 24 = 16

Example 3:

1
2
Input: 218
Output: false

分析

这是一个求2的N次方的题目,较为基础.
第一种解题方法:直接求是不是即可(暴力判断);
第二种解法:位运算,判断所有位数上仅有一位是1其他的是0即可求得。

C语言

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<stdio.h>
bool isPowerOfTwo(int n) {
if(n<=0)
{
return false;
}
else if(n==1||n==2)
{
return true;
}
while(n>1)
{
if(n%2==1)
{
return false;
}
else n=n/2;
}
return true;
}
int main()
{
int n=218;
printf("%d",isPowerOfTwo(n));
return 0;
}