Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Is Power Of Three(是否是3的幂)

From

LeetCode 326

Question

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

C++

class Solution {
public:
    bool isPowerOfThree(int n) {
        
        if(n>1){
            
            while(n%3==0){
               n=n/3;
            }
        }
        
        return n==1;
    }
};
class Solution {
public:
    bool isPowerOfThree(int n) {

      if(n>0){
            return 1162261467%n==0;
      }else{
          return false;
      }
	}
};

Java

public boolean isPowerOfThree(int n) {
    
    if( n > 1 ){
        
        while( n%3 == 0){
            
           n = n/3;
        }
    }
    
    return n == 1;
}