Is Power of Num

Is Power of Num

题目描述:

给定一个数字,要求判断这个数字是否是2的幂次所得到的。同理,我们判断这个数是不是3和4的幂次所得到。

例子:

具体描述见LeetCode231LeetCode326LeetCode342

解题思路:

解题的思路都是类似的,我们将数字转化为对应的n进制的数;在这个数是对应的幂次的情况下,首位是1,且其他位数全是0。通过以上的方法就可以判断是否是幂次的结果。

代码如下:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n <= 0) return false;
string res;
while(n){
char tmp = '0' + n % 2;
res = tmp + res;
n = n / 2;
}
for (int i = 1; i < res.size(); i++){
if (res[i] == '1') return false;
}
return true;
}
};
class Solution {
public:
bool isPowerOfThree(int n) {
if (n == 1) return true;
if (n < 3) return false;
string res;
while(n){
char tmp = '0' + n % 3;
res = tmp + res;
n = n / 3;
}
if (res[0] != '1') return false;
for(int i = 1; i < res.size(); i++){
if (res[i] != '0') return false;
}
return true;
}
};
class Solution {
public:
bool isPowerOfFour(int num) {
if (num == 1) return true;
if (num < 4) return false;
string res;
while(num){
char tmp = '0' + num % 4;
res = tmp + res;
num /= 4;
}
if (res[0] != '1') return false;
for (int i = 1; i < res.size(); i++){
if (res[i] != '0') return false;
}
return true;
}
};