Cracking The Coding Interview5.1
2014-04-18 01:17
232 查看
//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; }
相关文章推荐
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目6
- 《Cracking the Coding Interview》——第3章:栈和队列——题目4
- 《Cracking the Coding Interview》——第6章:智力题——题目5
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目8
- Cracking the Coding Interview Q2.4
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目11
- cracking the coding interview No1.1
- cracking the coding interview No1.7
- Cracking the coding interview--Q1.1
- Cracking the coding interview--Q1.3
- Cracking the coding interview--Q1.4
- Cracking the coding interview--Q17.5
- Cracking the Coding Interview – ch16,17,18
- Cracking the coding interview(中文版)
- Cracking the coding interview--Q1.7
- Cracking The Coding Interview 5.7
- 【Cracking the coding interview】Q1.2(反转字符串)
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目2
- Cracking the coding interview--Q4.2
- Cracking the coding interview--Q20.10