LeetCode 326. Power of Three

https://leetcode.com/problems/power-of-three/description/

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直到最好余数为1。注意边界值。
  • 第二种解法,int最大值在C/C++语言中与机器位长相关,32位下是2^32-1,Java中int是固定的32位,即2^32-1。那么可以算出来int下最大的3的幂为3^19=1162261467。只要能被它整除的必然是3的幂。
    • https://leetcode.com/problems/power-of-three/solution/
 1 //
 2 //  main.cpp
 3 //  LeetCode
 4 //
 5 //  Created by Hao on 2017/3/16.
 6 //  Copyright © 2017年 Hao. All rights reserved.
 7 //
 8 
 9 #include <iostream>
10 using namespace std;
11 
12 class Solution
13 {
14 public:
15     bool isPowerOfThree(int n)
16     {
17         if (n < 1) {
18             return false;
19         }
20         
21         while (n % 3 == 0) {
22             n /= 3;
23         }
24         
25         return n == 1;
26     }
27 
28     bool isPowerOfThree2(int n)
29     {
30         return n > 0 && 1162261467 % n == 0;
31     }
32 };
33 
34 int main(int argc, char* argv[])
35 {
36     Solution    testSolution;
37     
38     auto nums = {0, 1, 2, 3, 4, 6, 9, 27, 1162261467};
39     
40     for (auto num : nums)
41     {
42         cout << num << " isPowerOfThree ? " << testSolution.isPowerOfThree(num) << endl;
43         cout << num << " isPowerOfThree2 ? " << testSolution.isPowerOfThree2(num) << endl;
44     }
45     
46     return 0;
47 }
View Code
0 isPowerOfThree ? 0
0 isPowerOfThree2 ? 0
1 isPowerOfThree ? 1
1 isPowerOfThree2 ? 1
2 isPowerOfThree ? 0
2 isPowerOfThree2 ? 0
3 isPowerOfThree ? 1
3 isPowerOfThree2 ? 1
4 isPowerOfThree ? 0
4 isPowerOfThree2 ? 0
6 isPowerOfThree ? 0
6 isPowerOfThree2 ? 0
9 isPowerOfThree ? 1
9 isPowerOfThree2 ? 1
27 isPowerOfThree ? 1
27 isPowerOfThree2 ? 1
1162261467 isPowerOfThree ? 1
1162261467 isPowerOfThree2 ? 1
Program ended with exit code: 0
View Result

 

posted on 2018-01-26 15:08  浩然119  阅读(146)  评论(0编辑  收藏  举报