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");
};
时间: 2024-10-26 13:48:14