# Power of K问题

## 231. Power of Two

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

1   1
2   10
4   100
8   1000
16  10000
32  100000


class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0&&!(n&(n-1));
}
};


## 326. Power of Three

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

3的幂次方似乎没有什么特殊的性质（反正我没看出来），所以我们就要利用一下数学知识了，即:如果一个数是3的整数幂次方，那么其以3为底的对数必然是一个整数。

n=243时:

log(243) = 5.493061443340548    log(3) = 1.0986122886681098
==> log(243)/log(3) = 4.999999999999999


class Solution {
public:
bool isPowerOfThree(int n) {
double res=log10(n)/log10(3);
return (res-(int)(res))==0? true:false;
}
};


class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && (1162261467 % n == 0);
}
};


(然而你都知道3的幂次方有哪些数了你还算啥呀？！)

## 342. Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example: Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

1   0000 0001
4   0000 0100
16  0001 0000

2   0000 0010
8   0000 1000


class Solution {
public:
bool isPowerOfFour(int num) {
return num>0&&!(num&(num-1))&&(num&(0x55555555));
}
};


### 学籍管理系统文档

#### 北邮教务系统评教脚本

Published on September 17, 2017

#### 72.Edit distance

Published on September 17, 2017