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;
    }
};

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