[LeetCode 326,342][簡單]3的冪/4的冪

326.3的冪
題目鏈接
比較好想的是取對數法。

class Solution {
public:
    double eps = 1e-11;
    bool isPowerOfThree(int n) {
        if(n<=0)return 0;
        double pw = log2(n) / log2(3.0);
        return fabs(round(pw) - pw) < eps ? 1 : 0;
    }
};

另外可以找到int範圍內最大的冪,取模

static const auto io_speed_up = []() 
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    return 0; 
}();
class Solution {
public:
    bool isPowerOfThree(int n) {
        return n>0&&1162261467%n==0;
    }
};

342.4的冪
題目鏈接
比較顯然的思路是判斷是不是2的冪然後判斷是不是4的冪
假設已經知道是2的冪,那麼可以通過看2進制從低到高的奇數位是不是1來判斷。

static const auto io_speed_up = []() 
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    return 0; 
}();
class Solution {
public:
    bitset<32>odn = bitset<32>(0xaaaaaaaa);
    bool isPowerOfFour(int num) {
        bitset<32>n(num);
        return n.count()==1&&(n&odn).count()==0;
    }
};

或者可以通過n%3==1來判斷是不是4的冪。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章