Friday, October 13, 2017

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?

Solution:
Loop/ recursion should be straightforward.
The trick solution is to not use them.
Like we did in power of 2, since 3 is a prime number, any integer that is power of three should be a divisor of the biggest power of three in integer range. And any other integers are not be able to divided by that number.

 public boolean isPowerOfThree(int n) {  
     return (n>0 && 1162261467%n==0);  
   }  

No comments:

Post a Comment