Own version
public static bool IsPowerOfThree(int n) {
if (n == 1) {
return true;
}
double num = n;
bool isPower = false;
while (num >= 1) {
num = num / 3;
if (num == 1 && num == (int)num) {
return true;
}
}
return isPower;
}
Recursive version
public static bool IsPowerOfThree(int n) {
if (n == 1) {
return true;
} else if (n == 0 || n % 3 > 0) {
return false;
} else {
return IsPowerOfThree(n / 3);
}
}
Finally, there is a clever way to make use of the logarithm of the change of the formula to do, the high school has learned the bottom formula for log
AB = LogCB/logCA, then if N is a multiple of 3, then log3n must be an integer, we can write it as log by using the change formula3n = Log10N/log103, note here must use 10 as the base, can not use the natural number or 2 as the base, otherwise when the n=243 error, the reason please seeThis post. Now the question becomes a judgment log.10N/log103 is an integer, in C + + to determine whether the number A is an integer, we can use A-int (a) = = zero to determine, see the code is as follows:
class Solution {
public:
bool isPowerOfThree(int n) {
return (N> 0 && int(log10(N) /log10(3)) -log10(N) /log10(3) == 0);
}
};
From for notes (Wiz)
326. Is the square root of 3 ispowerofthree