NVIDIA Interview Question
Software Engineer / Developers@ CodeGeek
Incrementing M+=(p-1); like this will take to NOT to the bit but to the byte (p-1) & that could be beyond your actual array.
I think the actual question is "We need to copy certain bits that could be at the locations like p = 15 & q = 21. so in this case we need to just copy 21-15=6 bits."
I am assuming M to be of 4 bytes & N to be of 1 byte (if that is not the case then we will have to look for iterative solution)
int M1 = 0;
take another array suppose M1. Initialize it with 0.
Then copy N left shifted by to M1 and then "&" it with M. This will make all bits in M that are 1 and those are NOT 1 in N as 0.
M1 = M & (N<< ( 1<<p));
After that copy N to M.
M = M | (N << (1 << p));
@ YANG... assuming M is just a string ...meaning char *M = "100101110100101"
- CodeGeek January 13, 2011then pointer to string N say char *N = "10110"..
Now check for boundary condition.. ie
if(p>=0 && p<=strlen(M) && p<=q && q<=strlen(M) && q>=0)
if successful then check if(q-p == strlen(N)) if successful
increment M by (p-1) so as to make it point to pth bit in the string M.. i.e. M+=(p-1);
then in a loop
while(*M!= '\0' && *N!= '\0') // loop till end of string N and copy into string M
{
*M++ = *N++;
}