EXAMPLE:
Input: N = 10000000000, M = 10101, i = 2, j = 6
Output: N = 10001010100
we set all bits between i and j in N to 0, and make or operation with M<<i;
void setsubStringMN(int N,int M,int i,int j){
int max=~0;
int left = max - ((1<<j)-1);
int right = (1<<i)-1;
int mask = left|right;
return (N&mask)|(M<<i);
}
5.2 Given a (decimal - e g 3 72) number that is passed in as a string, print the binary representation If the number can not be represented accurately in binary, print “ERROR”.
5.3 Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation.
5.4 Explain what the following code does: ((n & (n-1)) == 0).
whether n is power of 2,or is zero.
5.5 Write a function to determine the number of bits required to convert integer A to integer B
Input: 31, 14 Output: 2
the problem is to calculate the number of bits differ between A and B. We xor A and B, and count the number of 1 in the results.
int numConvert(int A,int B){
int res=0;
for(A=A^B;A!=0;A=A>>1){
res+=(A&1);
}
return res;
}
5.6 Write a program to swap odd and even bits in an integer with as few instructions as possible (e g , bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc).
we reserve all odd bits by 101010,then shift them left to put them on even bits. We do the same operation on even bits.
int swapOddAndEven(int m){
return (m&0xAAAAAAAA)>>1|(m&0x55555555)<<1;
}
5.7 An array A[1 n] contains all the integers from 0 to n except for one number which is missing. In this problem, we cannot access an entire integer in A with a single operation. The elements of A are represented in binary, and the only operation we can use to access them is “fetch the jth bit of A[i]”, which takes constant time Write code to find the missing integer. Can you do it in O(n) time?
In the least significant bit of A[0..n], we known that the sum of 0 is equal to or one bigger than 1's. If we miss a odd number, the sum of 1 will small than 0's, if we miss a even number, the sum of 1 will equal to or one bigger than 0's. So, by looking at this condition, we will find a odd number missed or a even number missed.
If a odd number is missed, we recursive to all odd numbers of A[1..n], and like above, we can find the second least significant bit is 0 or 1.
We recursive one bit by one bit to the max length of n's binary represent(ceil(log2(n+1))).
int findMissNumber(int a[],int n){
vector<int> va;
for(int i=1;i<=n;i++){
va.push_back(a[i]);
}
n=ceil(log2(n+1))-1;
return findMissNum(va,0,n);
}
int findMissNum(vector<int> va,int index,int maxIndex){
if(index>maxIndex)return 0;
else{
vector<int> oddVa,evenVa;
for(int i=0;i<va.size();i++){
if(va[i].fetch(index)==0)evenVa.push_back(va[i]);
else oddVa.push_back(va[i]);
}
if(oddVa.size()>=evenVa.size()){
return findMissNum(evenVa,index+1,maxIndex)<<1|0;
}else{
return findMissNum(oddVa,index+1,maxIndex)<<1|1;
}
}
}