• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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 }

 

 

posted @ 2016-01-09 04:32  neverlandly  阅读(5857)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3