[LeetCode 869] Reordered Power of 2

题目

Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero.

Return true` if and only if we can do this in a way such that the resulting number is a power of 2.

Example 1:

Input: 1
Output: true

Example 2:

Input: 10
Output: false

Example 3:

Input: 61
Output: true

Note:

  • 1 <= N <= 10^9

思路

判断一个数 N 是否存在这样的排列(开始的位不能为0)为2的幂数可以利用 N 所拥有的1~9的数量与相同位数的2的幂数拥有的 0~9 的数量来进行比较。

即比如 1289,拥有的 0~9 的数量分别为: [0,1,1,0,0,0,0,0,1,9];
相同位数的2的幂数有:1024,2048,4096,8192 .很容易得到 12898192 拥有的数量相同。

Code in C++

(代码较长,可以更精简)

class Solution {
public:
    bool reorderedPowerOf2(int N) {
        if (N < 1)
            return false;

        vector<int> digits(10);
        int digitNum = 0, bound = 1;
        while (N) {
            digits[N%10]++;
            ++digitNum;
            N /= 10;
            bound *= 10;
        }

        int target = 1;
        while (target < bound/10) {
            target <<= 1;
        }

        bool ifMatch = true;
        while (target < bound) {
            int tmp = target;
            vector<int> tmpDigits(10);
            while (tmp) {
                tmpDigits[tmp%10]++;
                tmp /= 10;
            }

            for (int i = 0; i < 10; ++i) {
                if (tmpDigits[i] != digits[i]) {
                    ifMatch = false;
                    break;
                }
            }
            if (ifMatch)
                return true;

            ifMatch = true;
            target <<= 1;
        }

        return false;
    }
};

性能

通过的数量不多,无性能展示。

优化方案

  • 2的幂数不多, <10^9 的幂数只有30个,可以提前计算好,作为静态数组直接调用。
  • 观察每个2的幂数,可以发现每个幂数拥有的同一个数字的数量都没超过4个,可以把 0~9 的数量用2bit,或者更保险一点用3bit来存储,只需要30bit(<sizeof(uint32_t))。这样只需要比较一个32位的整数是否相等即可。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值