【LeetCode】326. Power of Three 3的冪(Easy)(JAVA)
阿新 • • 發佈:2020-12-22
技術標籤:Leetcodejavaleetcode演算法面試資料結構
【LeetCode】326. Power of Three 3的冪(Easy)(JAVA)
題目地址: https://leetcode-cn.com/problems/power-of-three/
題目描述:
Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3^x.
Example 1:
Input: n = 27
Output: true
Example 2:
Input: n = 0
Output: false
Example 3:
Input: n = 9
Output: true
Example 4:
Input: n = 45
Output: false
Constraints:
- -2^31 <= n <= 2^31 - 1
Follow up:Could you do it without using any loop / recursion?
題目大意
給定一個整數,寫一個函式來判斷它是否是 3的冪次方。如果是,返回 true ;否則,返回 false 。
整數 n 是 3 的冪次方需滿足:存在整數 x 使得 n == 3^x
進階:
- 你能不使用迴圈或者遞迴來完成本題嗎?
解題方法
- 對 n 判斷是否能整除 3, 如果能繼續迴圈,直到不能整除 3 為止
- 最後如果結果等於 1, 就說明是 3 的冪次方
class Solution { public boolean isPowerOfThree(int n) { if (n <= 0) return false; while (n % 3 == 0) { n /= 3; } return n == 1; } }
執行耗時:15 ms,擊敗了99.06% 的Java使用者
記憶體消耗:38.3 MB,擊敗了73.10% 的Java使用者
不用迴圈
- int 範圍內 3 的冪次方的最大值是 1162261467
- 所以所有 3 的冪次方: 1162261467 % n 的取餘都是 0,其他數都不等於 0
class Solution {
public boolean isPowerOfThree(int n) {
return (n > 0 && (1162261467 % n == 0));
}
}
執行耗時:17 ms,擊敗了46.11% 的Java使用者
記憶體消耗:38.3 MB,擊敗了69.07% 的Java使用者