博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
326. Power of Three
阅读量:7026 次
发布时间:2019-06-28

本文共 890 字,大约阅读时间需要 2 分钟。

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?

解决方法:

1、Recursive Solution

public boolean isPowerOfThree(int n) {    return n>0 && (n==1 || (n%3==0 && isPowerOfThree(n/3)));}

2、Iterative Solution

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

数学方法

1、找到3的n次方的最大整数,检查是否为输入的整数倍

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

或者更简单一点,3的n次方的最大值maxPowerOfThree = 1162261467。

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

2、log10(n) / log10(3)返回整数

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

reference

转载于:https://www.cnblogs.com/CarryPotMan/p/5343690.html

你可能感兴趣的文章
工厂方法模式
查看>>
360安全卫士怎么登录问题
查看>>
linux下的DNS缓存服务
查看>>
实现一键分享的代码
查看>>
详解Linux运维工程师必备技能
查看>>
[20181109]12c sqlplus rowprefetch参数5
查看>>
bupt summer training for 16 #1 ——简单题目
查看>>
【Udacity】朴素贝叶斯
查看>>
shader 讲解的第二天 把兰伯特模型改成半兰泊特模型 函数图形绘制工具
查看>>
python3.5安装Numpy、mayploylib、opencv等额外库
查看>>
优雅绝妙的Javascript跨域问题解决方案
查看>>
Java 接口技术 Interface
查看>>
函数草稿
查看>>
织梦系统学习:文章页当前位置的写法(自认对SEO有用)
查看>>
PHP经验——PHPDoc PHP注释的标准文档(翻译自Wiki)
查看>>
vue input输入框长度限制
查看>>
深入理解Java虚拟机(类加载机制)
查看>>
在500jsp错误页面获取错误信息
查看>>
iOS-CALayer遮罩效果
查看>>
为什么需要版本管理
查看>>