1. 程式人生 > 其它 >[LeetCode] 1780. Check if Number is a Sum of Powers of Three

[LeetCode] 1780. Check if Number is a Sum of Powers of Three

Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false.

An integer y is a power of three if there exists an integer x such that y == 3x.

Example 1:

Input: n = 12
Output: true
Explanation: 12 = 31 + 32

Example 2:

Input: n = 91
Output: true
Explanation: 91 = 30 + 32 + 34

Example 3:

Input: n = 21
Output: false

Constraints:

  • 1 <= n <= 107

判斷一個數字是否可以表示成三的冪的和。

給你一個整數 n ,如果你可以將 n 表示成若干個不同的三的冪之和,請你返回 true ,否則請返回 false 。

對於一個整數 y ,如果存在整數 x 滿足 y == 3x ,我們稱這個整數 y 是三的冪。

來源:力扣(LeetCode)
連結:https://leetcode.cn/problems/check-if-number-is-a-sum-of-powers-of-three
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

這是一道數學題,因為三的冪在 Integer 範圍內就那麼幾個數字,其實暴力列舉也是可以通過的。這裡我提供一個遞迴的思路。

  • 因為 3 的 0 次冪是 1,所以如果 n == 1,返回 true
  • 如果這個數字是 3 的倍數,那麼我們就把他除以 3,看看 n / 3 是不是 3 的次冪
  • 如果這個數字是 3 的倍數 + 1,那麼我們把它減一,看看 (n - 1) / 3 是不是 3 的次冪

唯一不行的 case 是如果這個數字是 3 的倍數 + 2,那麼他一定無法被若干個不同的三的冪組合,因為最後的 2 不能再拆分成 1 + 1 了。

時間O(1) - 其實接近於 O(1) 的時間,因為操作複雜度並不完全因著 n 的增大而增大

空間O(1)

Java實現

 1 class Solution {
 2     public boolean checkPowersOfThree(int n) {
 3         if (n == 1) {
 4             return true;
 5         }
 6         if (n % 3 == 0) {
 7             return checkPowersOfThree(n / 3);
 8         } else if (n % 3 == 1) {
 9             return checkPowersOfThree((n - 1) / 3);
10         }
11         return false;
12     }
13 }

LeetCode 題目總結