CareerCup-5.1

简介:

You are given two 32-bit numbers, N and M, and two bit positions, i and j Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j)

EXAMPLE:

Input: N = 10000000000, M = 10101, i = 2, j = 6 Output: N = 10001010100

第一个方法是我的思路 第二个是参考答案的思路实现的


#include <iostream>
#include <bitset>
using namespace std;
typedef int Data;

void setBits(bitset<32>* N, bitset<32>* M, int i, int j)
{
    *N = *N^(*N<<(32-j+i-1)>>(32-j-1))^(*M<<i);
};

void setBits2(bitset<32>* N, bitset<32>* M, int i, int j)
{
    bitset<32> t((~0<<(j+1)|((1<<i)-1)));
    *N = t&*N|(*M<<i);
};

int main()
{
    bitset<32> N((string)"10000000000");
    bitset<32> M((string)"10101");
    int i=2, j=6;
    setBits2(&N, &M, i, j);
    cout<<N<<endl;
    system("pause"); 
};


目录
相关文章
careercup-C和C++ 13.7
13.7 写一个函数,其中一个参数是指向Node结构的指针,返回传入数据结构的一份完全拷贝。 Node结构包含两个指针,指向另外两个Node。 C++实现代码: typedef map NodeMap; Node* copy_recursive(Node *cur, NodeMap &no...
704 0