Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
A daily programming problem
Title Description
Given an integer, write a function to determine if it is a power of three.
Title effect: Given an integer, it is determined whether the integer. 3
n-th power
Sample
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
python Solution
class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n>0 and 1162261467 % n == 0
Runtime: 96 MS
Memory Usage: 13.9 MB
title after reflection:
- This should be the easiest way to write, but not the fastest wording.
- 1162261467 is the greatest integer 32-bit signed integer 3 inside the acceptable power.
C language Solution
bool isPowerOfThree(int n){
return n>0?1162261467 % n == 0:false;
}
Runtime: 12 ms, faster than 82.84% of C online submissions for Power of Three.
Memory Usage: 7.5 MB, less than 50.00% of C online submissions for Power of Three.
题后反思:无
bool isPowerOfThree(int n){
while(n>2)
{
if (n%3)
return false;
n /= 3;
}
return n == 1;
}
Runtime: 24 ms
Memory Usage: 7.5 MB
This paper is my personal understanding, if the wrong place welcome comments below tell me, I promptly corrected, common progress