星期二, 二月 23, 2016

326. Power of Three

Given an integer, write a function to determine if it is a power of three.

Follow up:

Could you do it without using any loop / recursion?

 

结题思路:

1、判断一个数是否是3的次方数,一个比较直接的方法是循环,判断n的因子是否全为3

class Solution {

public:

    bool isPowerOfThree(int n) {

        if(n==0)return false;

        while(n!=1){

            if(n%3)return false;

            n/=3;

        }

        return true;

    }

};

2、若不使用循环或递归,可以先求出tmp=log3(n),再求3^tmp,判断是否与n相等。Log3(n)=log(n)/log(3)=log10(n)/log10(3)。注意在使用logpow方法时,得到的数都是double,在转换为int时,可能要考虑到近似问题。建议首先将double转换为float,在将float转换为int

float a = 6.7f;

float b = a * 10;

int c = a * 10;

int d = b;

printf( "%d", c ); // 输出 66

printf( "%d", d ); // 输出 67

在解释结果前,得先了解几个知识点:

1. 即使在表达范围内,浮点数(floatdoublelong double)也不能精确表达每一个实数。

比如float可以精确表达67.0f,可以精确表达6.69999980926513671875f,但不能精确表达6.7f

当不能精确表达时,选择一个最接近的能精确表达的数,比如float6.69999980926513671875f来表达6.7f

2. 浮点数计算使用80387数字协处理器,把每一个浮点数载入80bits的临时实数中,进行计算,结果然后再放回。

3. 高精度浮点数转化为低精度浮点数时,使用低精度浮点数能表示的最接近的数;浮点数转化为整型时,直接取整数部分。

于是流程如下:

float a = 6.7f;   // a 6.69999980926513671875f

float b = a * 10; // 计算结果66.9999980926513671875l 放入 float 中时,变为67.0f,因为67.0ffloat能表示的,且最接近66.99……的数。

int c = a * 10;   // 计算结果66.9999980926513671875l 整数部分 66

int d = b;        // 67.0f 整数部分 67

可见,差别在于C是由long double直接取整数部分,而dlong double放到float后再取的整数部分,奥妙就在"long double放到float"这一阶段。

 

来自 <http://biancheng.dnbcw.info/c/434925.html>

 

 

class Solution {

public:

    bool isPowerOfThree(int n) {

        if(n==0)return false;

        double tmp=(log(n)/log(3));

        float tf=tmp*10;

        int ti=tf/10;

        if(pow(3,ti)==n)return true;

        return false;

    }

};

3、在discussion上看到使用fmod方法

头文件:math.h

用法:double fmod(double x,double y)

功能:计算xy的模

举例:

#include<stdio.h>

#include<math.h>

void main()

{

double a=2.8,b=0.2,c=0.0;

c=fmod(a,b); 

printf("a=%.16lf,b=%.16lf,c=%.16lf\n",a,b,c);

getch();

}

 

输出:

a=2.7999999999999998,b=0.2000000000000000,c=0.1999999999999997

class Solution {

public:

    bool isPowerOfThree(int n) {

        if(n==0)return false;

        return fmod(log10(n)/log10(3),1)==0;

    }

};

4、。。。。。。。。

没有评论:

发表评论