leetcode [#326]

目录

题目

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
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public boolean isPowerOfThree(int n) {
if(n == 0) return false;
if(n == 1) return true;
boolean result = false;
String str = Integer.toString(n);
int len = str.length();
if(n == Math.pow(3, (2 * len - 1)) || n == Math.pow(3, (2 * len))){
result = true;
}
return result;
}
}

注意事项

  1. 题目要求不要用任何循环或者递归。
  2. 找到3的所有次幂的规律(除去0次幂):

    3^1 = 3, 3^2 = 9: 结果长度1位;
    3^3 = 27, 3^4 = 81: 结果长度2位;
    3^5 = 243, 3^6 = 729: 结果长度3位;
    3^7 = 2187, 3^8 = 6561: 结果长度4位;
    3^9 = 19683, 3^10 = 59049: 结果长度5位;
    3^11 = 177147, 3^12 = 531441:结果长度6位;
    … …
    3^(2*k-1) = … , 3^(2*k) = … :结果长度k位;

  3. 因此,拿到一个整数,先判断其长度,在长度已知的情况下,该数是3的某次幂只可能有两种情况,判断是否是二者之一即可。