zoukankan      html  css  js  c++  java
  • Leetcode: 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?

    Recursion:

    1 public class Solution {
    2     public boolean isPowerOfThree(int n) {
    3         if (n <= 0) return false;
    4         if (n == 1) return true;
    5         else if (n%3 == 0) return isPowerOfThree(n/3);
    6         else return false;
    7     }
    8 }

    Iteration:

     1 public class Solution {
     2     public boolean isPowerOfThree(int n) {
     3         if (n <= 0) return false;
     4         while (n != 1) {
     5             if (n%3 != 0) break;
     6             n /= 3;
     7         }
     8         return n==1;
     9     }
    10 }

    Math: https://leetcode.com/discuss/78532/a-summary-of-all-solutions

    It's all about MATH...

    Method 1

    Find the maximum integer that is a power of 3 and check if it is a multiple of the given input. (related post)

    1 public boolean isPowerOfThree(int n) {
    2     return n>0 && Math.pow(3, (int)(Math.log(0x7fffffff)/Math.log(3)))%n==0;
    3 }

    Note that

    Math.pow(3, (int)(Math.log(0x7fffffff)/Math.log(3)))
    

    returns the maximum integer that is a power of 3

    Method 2

    If log10(n) / log10(3) returns an int, then n is a power of 3. (original post). But be careful here, you cannot use log (natural log) here, because it will generate round off error.

    1 public boolean isPowerOfThree(int n) {
    3   return (Math.log10(n) / Math.log10(3)) % 1 == 0;
    5 }

     

  • 相关阅读:
    jQuery 选择器
    pf_ring 编译移植
    Android wifi 扫描机制
    wifi 万能钥匙协议
    linux下CJson使用
    libxml -- 解析 XML 文档
    关闭浏览器复制行为
    Ubuntu 语言设置
    Socket编程之非阻塞connect
    Java多维数组
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5115390.html
Copyright © 2011-2022 走看看