leetcode326
問題就是判斷一個數n是否爲3的power。
比如:1 3 9 81 243 …… 這些都是
思路:使用
開始我使用了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;
}
};