您的位置:首页 > 其它

71-Power of Three

2016-05-17 12:29 288 查看
Power of Three My Submissions QuestionEditorial Solution

Total Accepted: 41963 Total Submissions: 113431 Difficulty: Easy

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?

先给出有循环的答案,因为事先用map或set存储后面比较的方法并没有更快

21038 / 21038 test cases passed.

Status: Accepted

Runtime: 136 ms

beats65.89%

class Solution {
public:
bool isPowerOfThree(int n) {
if(n==0)return false;
while(n!=1){
if((n%3)!=0)return false;
n=n/3;
}
return true;
}
};


用map实现反而更慢。。

Submission Details

21038 / 21038 test cases passed.

Status: Accepted

Runtime: 416 ms

beats:0.79%

class Solution {
public:
bool isPowerOfThree(int n) {
map<int,int> map3;
map3[1]=1;
map3[3]=1;
map3[9]=1;
map3[27]=1;
map3[81]=1;
map3[243]=1;
map3[729]=1;
map3[2187]=1;
map3[6561]=1;
map3[19683]=1;
map3[59049]=1;
map3[177147]=1;
map3[531441]=1;
map3[1594323]=1;
map3[4782969]=1;
map3[14348907]=1;
map3[43046721]=1;
map3[129140163]=1;
map3[387420489]=1;
map3[1162261467]=1;
if(map3.count(n))return true;
else return false;
}
};


Power of Three

Submission Details

21038 / 21038 test cases passed.

Status: Accepted

Runtime: 392 ms

事实上仅仅比map快一点点

#define IMAX numeric_limits<int>::max()
class Solution {
public:
bool isPowerOfThree(int n) {
set<int> s;
s.insert(1);
s.insert(3);
s.insert(9);
s.insert(27);
s.insert(81);
s.insert(243);
s.insert(729);
s.insert(2187);
s.insert(6561);
s.insert(19683);
s.insert(59049);
s.insert(177147);
s.insert(531441);
s.insert(1594323);
s.insert(4782969);
s.insert(14348907);
s.insert(43046721);
s.insert(129140163);
s.insert(387420489);
s.insert(1162261467);
if(s.count(n))return true;
else return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: