zoukankan      html  css  js  c++  java
  • leetcode 326. Power of Three(不用循环或递归)

    leetcode 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?

    题意是判断一个数是否是3的幂,最简单的也最容易想到的办法就是递归判断,或者循环除。

    有另一种方法就是,求log以3为底n的对数。类似 如果n=9,则结果为2,如果是10,则结果肯定不是个整数。所以第一次提交如下:

    public class Solution {
       
        public boolean isPowerOfThree(int n) {
            if(0 == n)
                return false;
            double res = Math.log(n)/Math.log(3);
            return Math.floor(res) == Math.ceil(res);
           
        }
    }
    

    但是并没有ac,原因是243的时候出错,后来分析发现是因为java 浮点数的原因。参考别人的修改了下,如下:

    public class Solution {
        private static final double epsilon = 10e-15;
    
        public boolean isPowerOfThree(int n) {
            if(0 == n)
                return false;
            double res = Math.log(n)/Math.log(3);
            //return Math.floor(res) == Math.ceil(res);
            return Math.abs(res - Math.round(res)) < epsilon;
        }
    }
    

    ac

  • 相关阅读:
    阿里云与物理服务器
    ## 100个网路基础知识##
    Linux 中vim编辑器
    Linux 目录结构及增删改查
    Linux 命令行常用快捷键
    XSS劫持cookie登录
    Tomcat
    centos 6.5 搭建DHCP实验
    centos 6.5 系统故障分析实验
    LVM的创建及管理
  • 原文地址:https://www.cnblogs.com/tina-smile/p/5115810.html
Copyright © 2011-2022 走看看