二进制转换

看到一位大佬的写法,感觉太有意思了,非常巧妙,学习一下。
题目描述

A non-empty array A consisting of N non-negative integers is given.
Its binarian is defined as:

binarian(A)=pow2(A[0]) + pow2(A[1]) + ... + pow2(A[N-1])
pow2(K) = 2 ^ K

For example, the binarian of array A such that:
[1, 5, 4]
equals 50:

binarian(A)=pow2(A[0]) + pow2(A[1])+ pow2(A[2]) = pow2(1)+ pow2(5)+ pow2(4) = 2 + 32 + 16 = 50

Write a function:

class Solution{public int solution(int[] A)};
that, given an array A consisting of N non-negative integers, returns the length of the shortest array that has the same binarian as array A.
For example, given array A such that [1,0,2,0,0,2]
the function should return 3 because:
• the binarian of A is 13

• array B such that B[0] = 3, B[1] = 2 and B[2] = 0 also has a binarian of 13,

• there is no shorter array with a binarian of 13.

Write an efficient algorithm for the following assumptions:
• N is an integer within the range [1..100,000]
• each element of array A is an integer within the range[0..10,000].
const int N = 10100;

class Solution{
public:
    int solution(vector<int>& A)
    {
        bitset<N> f;
        for(int i = 0; i < A.size(); i++)
        {
            int j = A[i];
            bool flag = true;
            while(flag)
            {
                flag = f[j] & flag;
                if(flag)
                    f[j++] = false;
                else
                    f[j++] = true;
            }
        }
        return f.count();
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值