342. Power of Four

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 Three 和 231. 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;
}

你可能感兴趣的:(342. Power of Four)