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

    Credits:
    Special thanks to @dietpepsi for adding this problem and creating all test cases.

    题意:判断给定的数是否为3的n次方
    follow up:要求不使用循环或递归

    方法一:直接判断

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

    没有想出不使用循环的解决方法,最后参考LeetCode提供的参考答案

    方法二:将给定数n转换成3进制形式,再判断转换的3进制是否为高位为1,低位全为0的形式,是该形式则n是3的次方数;否则不是。

    原理同Power Of Two的方法:http://www.cnblogs.com/zeroingToOne/p/8186009.html

    实现:

    Integer类的:static String toString(int i, int radix)方法:返回10进制i的radix进制形式。将给定数n转换为3进制;
    String类的:boolean matches(String regex) 方法:返回此字符串是否匹配给定的正则表达式。判断n的3进制形式是否满足条件

    public boolean isPowerOfThree(int n){
            return Integer.toString(n, 3).matches("^10*$");
        }

    方法三:由于输入的是int型,正数范围为0~2^31,在此范围内,3的最大次方数为3^19 = 11622 61467.因此只要看3^19能否被给定的数n整除即可。

    public boolean isPowerOfThree(int n){
            return n > 0 && 1162261467 % n == 0;
        }

    方法四:

    利用Math类的log10(double a)方法,返回 double 值的底数为 10 的对数。
    只需要判断i是否为整数即可。

    public boolean isPowerOfThree(int n){
            return (Math.log10(n) / Math.log10(3)) % 1 == 0;
        }
  • 相关阅读:
    zblog数据库配置文件
    zblog忘记后台密码怎么办 官方解决方案
    炫光生成器 一键生成炫光背景
    织梦channel标签中currentstyle不生效
    织梦list/arclist标签调用文章内容
    织梦添加视频前台无法播放
    织梦后台上传mp4视频不显示
    wordpress安装后首页无法进入 The file 'wp-config.php' already exists
    关于java中jdk的环境变量配置
    java中三大集合框架
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/8214186.html
Copyright © 2011-2022 走看看