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?

链接:

https://leetcode.com/problems/power-of-three/?tab=Description

3/7/2017

不满足题目的解法,注意n == 1也是true

1 public class Solution {
2     public boolean isPowerOfThree(int n) {
3         if (n == 1) return true;
4         if (n == 2) return false;
5         while (n > 3 && n % 3 == 0) n /= 3;
6         if (n == 3) return true;
7         return false;
8     }
9 }

可以简化为

 1 public class Solution {
 2     public boolean isPowerOfThree(int n) {
 3         if (n < 1) {
 4             return false;
 5         }
 6 
 7         while (n % 3 == 0) {
 8             n /= 3;
 9         }
10 
11         return n == 1;
12     }
13 }

题目给出的4种解法,然而并不觉得比native解法好到哪里去。

https://leetcode.com/articles/power-of-three/

posted @ 2017-03-08 07:05  panini  阅读(104)  评论(0编辑  收藏  举报