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

遇到这题,首先想到的就是二分法查找指数使得 3 的 x 次方小于 n, 然后用 n - 3 的 x 次方的值再进行递归, 思路是对的,但是为什么能这么做, 刚才思考了一下, 应该是因为对于任何整数 n(n >= 1),3 ^ 0 + 3 ^ 1 + 3 ^ 2 +…+3 ^ (x - 1) < 3 ^ x, 由于每个 x 都只能出现一次, 所以我们在递归的时候需要提供上一次的 x, 本次的 x 不得大于或者等于上一次的 x



impl Solution {
    fn rc(n: i32, limit: u32) -> bool {
        if n == 0 {
            return true;
        }
        let mut low = 0u32;
        let mut high = 15u32;
        while low < high {
            let m = (low + high) / 2;
            let curr = 3i32.pow(m);
            if curr < n {
                low = m + 1;
                continue;
            }
            high = m;
        }
        if 3i32.pow(low) > n {
            if low == 0 {
                return false;
            }
            low -= 1;
        }
        if low >= limit {
            return false;
        }
        Solution::rc(n - 3i32.pow(low), low)
    }
    pub fn check_powers_of_three(n: i32) -> bool {
        Solution::rc(n, 15)
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值