您的位置:首页 > 其它

342. Power of Four

2016-05-22 11:37 197 查看

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?

Analysis:

用了一种大概比较‘笨’的方法,把所有可能值全部列举出来,但也不失为一种方法。

关于其他方法详见:326. Power of Three231. Power of Two

Source Code(C++):

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
bool isPowerOfFour(int num) {
vector<int> v;
v.push_back(0x00000001);v.push_back(0x00000004);v.push_back(0x00000010);v.push_back(0x00000040);v.push_back(0x00000100);v.push_back(0x00000400);v.push_back(0x00001000);v.push_back(0x00004000);
v.push_back(0x00010000);v.push_back(0x00040000);v.push_back(0x00100000);v.push_back(0x00400000);v.push_back(0x01000000);v.push_back(0x04000000);v.push_back(0x10000000);v.push_back(0x40000000);
if (find(v.begin(), v.end(), num) == v.end()){
return false;
}
else {
return true;
}
}
};

int main() {
Solution sol;
cout << sol.isPowerOfFour(16);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: