NVIDIA Interview Question
Software Engineer / DevelopersQuestion says: bitwise reverse a very long character string
If it is bytewise, then we may do following:
1.Scan string characters from both side (front and end) using two variable say i and j.
2.Swap str[i] and str[j]
3.increment i and decrement j
4.Repeat 2 and 3 until i>=j
for(i=0,j=strlen(str);i<j;i++,j--)
swap(str[i],str[j]);
I can't think of any better soln. Other ideas pls.
I think u r wrong..
XOR the String with all ones...
Let Give:101011100
XOR with 111111111
we get 010100011=~(givenstring)
The question is to reverse the string. i.e., 1001101 should result in 1011001. What you answered is complement of all bits.
x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1); //Only this line if 2 bits can represent the integer
- Anurag Singh January 27, 2011x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2); //This and all above if 4 (or less) bits can represent the integer
x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4); //This and all above if 8 (or less) bits can represent the integer
x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8); //This and all above if 16 (or less) bits can represent the integer
x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16); //This and all above if 32 (or less) bits can represent the integer
So all above four lines can be used for any integer (32 bit integer)
For input 1001101 i.e. decimal 77, 1st three lines will give the result as input can be taken as 8 bits (01001101), so after 3rd line of execution, value of x will be:
10110010