326. Power of Three

    xiaoxiao2021-03-25  88

     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?

    递归:

    public class Solution { public static boolean isPowerOfThree(int n) { int c=0; if(n<=0) return false; if(n==1) return true; else if(n%3==0) { return isPowerOfThree(n/3); } else return false; } }

    迭代:

    public class Solution { public boolean isPowerOfThree(int n) { if (n <= 0) return false; while (n != 1) { if (n%3 != 0) break; n /= 3; } return n==1; } }

    数学方法:

    public static boolean isPowerOfThree1(int n) { double res=Math.log(n)/Math.log(3); return Math.abs(res - Math.rint(res))< 0.0000000001; }

    转载请注明原文地址: https://ju.6miu.com/read-20252.html

    最新回复(0)