Power of Three

来源:互联网 发布:西游之路仙童进阶数据 编辑:程序博客网 时间:2024/04/29 15:05

Power of Three

作者:money
标签:leetcode,C++

问题:

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?

问题分析:

判断一个数是否为3的n次方,选择通过不断除三求余判断。代码效率是有史以来最差的一次。。。

实现代码:

#include <iostream>#include <string>#include <vector>// submit these code to leetcode// beginusing namespace std;class Solution {public:    bool isPowerOfThree(int n) {        int mods=0;        bool istrue=true;        if(n<=0)            istrue=false;        else          {          while(n>0&&n!=1)          {            mods=n%3;                if(mods==0)                    {n=n/3;}                else                   { istrue=false;                    break;}            cout<<"mods="<<mods<<endl;            cout<<"istrue="<<istrue<<endl;            cout<<"n="<<n<<endl;          }          }          return istrue;    } };// end// submit these code to leetcodeint main(){  Solution s;  int test;  bool a;  cin>>test;  a=s.isPowerOfThree(test);  //test case  if(a)    std::cout<<"true"<<endl;  else    cout<<"false"<<endl;  return 0;} 

其他解法

1、递归求余及除3:

public boolean isPowerOfThree(int n) {    return n>0 && (n==1 || (n%3==0 && isPowerOfThree(n/3)));}

2、简洁写法:

public boolean isPowerOfThree(int n) {    if(n>1)        while(n%3==0) n /= 3;    return n==1;}

3、int中最大的3的n次方数为1162261467
任何3n 均为该数的因子:

public boolean isPowerOfThree(int n) {    return n > 0 && (1162261467 % n == 0);}

4、通过求

n=3k

k=log3n=log10nlog103

需要注意的是可能存在float类型溢出的情况,貌似使用自然对数ln会出现上述情况。然后判断k是否能被1整除。

public boolean isPowerOfThree(int n) {    return (Math.log10(n) / Math.log10(3)) % 1 == 0;}
0 0
原创粉丝点击