首页 > 其他分享 >[LeetCode] 1780. Check if Number is a Sum of Powers of Three

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

时间:2022-12-09 07:22:58浏览次数:55  
标签:return 1780 Sum Number Example integer false true LeetCode

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 题目总结

标签:return,1780,Sum,Number,Example,integer,false,true,LeetCode
From: https://www.cnblogs.com/cnoodle/p/16967942.html

相关文章