leetcode 326_log log10 精度問題

leetcode326
問題就是判斷一個數n是否爲3的power。
比如:1 3 9 81 243 …… 這些都是
思路:使用log3n 判斷。c++中math.h中只有log和log10兩個函數,所以需要使用換底公式。
開始我使用了log,但是再243的時候精度不夠,後來改爲log10,遂ac

代碼如下,要單獨考慮負數和1的情況。

//
//  main.cpp
//  326
//
//  Created by Wang Bill on 7/26/16.
//  Copyright © 2016 Wang Bill. All rights reserved.
//

#include <iostream>
#include <math.h>
using namespace std;

class Solution {
public:
    bool isPowerOfThree(int n) {
        if (n<=0) {
            return false;
        }
        if (n==1) {
            return true;
        }
        double esp=1e-10;
        int r = log10(n)/log10(3);
        double rr = log10(n)/log10(3);
        if (rr-r>esp) {
            return false;
        }
        else return true;
    }
};

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