0
点赞
收藏
分享

微信扫一扫

LeetCode Top Interview Questions 326. Power of Three (Java版; Easy)


​​welcome to my blog​​

LeetCode Top Interview Questions 326. Power of Three (Java版; Easy)

题目描述

Given an integer, write a function to determine if it is a power of three.

Example 1:

Input: 27
Output: true
Example 2:

Input: 0
Output: false
Example 3:

Input: 9
Output: true
Example 4:

Input: 45
Output: false
Follow up:
Could you do it without using any loop / recursion?

第一次做; 数学分析:3^19的因数只有20个, 分别是3^0,…3^19

class Solution {
public boolean isPowerOfThree(int n) {
// 1162261467 is 3^19, 3^20 is bigger than int
return (n>0 && 1162261467%n==0)
}
}

第一次做;特殊情况:0不是3的幂, 1是3的幂; 三的幂的因数只有三; %3==0的数不一定是3的幂, 比如15, 45; 但3的幂%3==0

class Solution {
public boolean isPowerOfThree(int n) {
if(n==0)
return false;
if(n==1)
return true;
if(n%3==0){
if(n==3)
return true;
else
return isPowerOfThree(n/3);
}
return false;
}
}

​​力扣官方题解​​; 3^19的因数只有3^0, 3^1, 3^2,…3^19

LeetCode Top Interview Questions 326. Power of Three (Java版; Easy)_算法

​​力扣官方题解​​; 比我的递归逻辑清晰

public class Solution {
public boolean isPowerOfThree(int n) {
if (n < 1) {
return false;
}

while (n % 3 == 0) {
n /= 3;
}

return n == 1;
}
}


举报

相关推荐

0 条评论