# C#LeetCode刷题之#326-3的幂（Power of Three）

Given an integer, write a function to determine if it is a power of three.

Input: 27

Output: true

Input: 0

Output: false

Input: 9

Output: true

Input: 45

Output: false

Follow up:Could you do it without using any loop / recursion?

```public class Program {

public static void Main(string[] args) {
var n = 25;
var res = IsPowerOfThree(n);
Console.WriteLine(res);

n = 16;
res = IsPowerOfThree2(n);
Console.WriteLine(res);

n = 27;
res = IsPowerOfThree3(n);
Console.WriteLine(res);

}

private static bool IsPowerOfThree(int n) {
//先看原值是否能被3整除
//若不能整除，不是3的幂；
//若能整除，继续往下，直接<=1时为止
//最后判断值是否为1即可
while(n % 3 == 0 && (n /= 3) > 1) { }
return n == 1;
}

private static bool IsPowerOfThree2(int n) {
//负数肯定不满足题意
if(n <= 0) return false;
//找到整型范围内最大的3的幂
//var maxPower = (int)Math.Pow(3, (int)(Math.Log10(int.MaxValue) / Math.Log10(3)));
var maxPower = 1162261467;
//这个值是否能被n整除
return maxPower % n == 0;
}

private static bool IsPowerOfThree3(int n) {
//基于高中数学的一些技巧
var x = Math.Log10(n) / Math.Log10(3);
//这种解法有点赖皮，仅给大家一些思路吧
//IDE给出的警告请无视
return (int)x - x == 0;
}

}```

```False
False
True```

(2)