Vulkan

Cracking The Coding Interview5.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 <vector>
using namespace std;
/***纯粹是计算题***/
int mset(int N, int M, int i, int j)
{
	int t = 1;
	t =t << j-i+1;
	t --;//得到0000 0000 0001 1111
	t=t<<i;
	t = ~t;//得到1111 1111 1100 00011
	M= M<<i;
	int K = t & N;//将N对应位置set为0
	K = K|M;
	return K;
}

void print(int p)
{
	vector<int> v;
	for (int k = 0;k<32; k++)
	{
		int t = p&1;
		v.push_back(t);
		p=p>>1;
	}
	for (int i = v.size()-1;i>-1; i--)
	{
		cout<<v[i]<<" ";
	}
	cout<<endl;
}
int main()
{
	int n = 1<<10, m = 21;
	print(n);
	print(m);
	cout<<"====================================================================="<<endl;
	for (int t = 0;t<20;t++)
	{
		int ss= mset(n, m,t,t+4);
		print(ss);
	}
	
	return 0;
}

posted on 2014-04-18 01:17  Vulkan  阅读(149)  评论(0编辑  收藏  举报

导航