判断一个数字是否可以表示成三的幂的和

题目

给你一个整数 n ,如果你可以将 n 表示成若干个不同的三的幂之和,请你返回 true ,否则请返回 false 。

对于一个整数 y ,如果存在整数 x 满足 y == 3x ,我们称这个整数 y 是三的幂。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-if-number-is-a-sum-of-powers-of-three

1.从最大的3的幂开始,如果大于等于剩余数字,就应当使用这一幂次(因为剩下的所有幂次加起来也比它小)。看最后是否能减到0。

class Solution {
public:
    bool checkPowersOfThree(int n) {
        vector<int> threes{1};
        while (threes.back() < n)
            threes.emplace_back(threes.back() * 3);
        for (int i = threes.size() - 1; i >= 0; --i) {
            if (n >= threes[i])
                n -= threes[i];
        }
        return n == 0;
    }
};
 

2.转化为三进制
可以将 n 表示成若干个不同的三的幂之和。
三进制表示
3 0 3^0 30=1 3 1 3^1 31=10 3 2 3^2 32=100 3 3 3^3 33=1000 3 4 3^4 34=10000 3 1 3^1 31=1…0
那么n如果可以由上面这些的一些数相加而得,那么一定是转换为三进制不含2

class Solution {
    public boolean checkPowersOfThree(int n) {
        return n<2 || (n%3 != 2 && checkPowersOfThree(n/3));
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值