Leetcode 326 Power of Three

来源:互联网 发布:广州网络宽带资费标准 编辑:程序博客网 时间:2024/05/22 06:41

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?


第一种方法直接用while




public class Solution {    public boolean isPowerOfThree(int n) {        if(n==1){            return true;        }            while(n>0){            int m=n%3;        if(m==0){            n=n/3;                          if(n==1){                return true;                       }                          }         else{                return false;                       }           }     return false;    }}


第二种用递归

public class Solution {    public boolean isPowerOfThree(int n) {        if(n==1){            return true;        }           if(n>1){           int m = n/3;           if(m>0){               return isPowerOfThree(n/3)&&(n%3==0);           }           }     return false;    }}


第三种直接math哈哈哈

public boolean isPowerOfThree(int n) {    if(n==0) return false;     return n == Math.pow(3, Math.round(Math.log(n)/Math.log(3)));}



0 0
原创粉丝点击