Friday, June 10, 2011

EFI interview - 3

Problem: Two integers given, N and M. Suppose M = 10101 (binary system), write code to change N's 2nd to 6th bits to M. For example, N = 100001000, M = 10101, the result is expected to be 101010100.

当时瞎折腾了一通,并没有完全解出来。不过基本思路是有的,回到旅馆之后整理了一下思路,大致应该这么做:

M << 2 first, to move the binary numbers into bit 2~6. Then if we can clear bits 2~6 in N, say the cleared N is N1, then what left is to do N1 | M<<2.

But how to clear bits 2~6 in N? It seems N & ~1111100 can do it. So, could it be done with (N & (~1111100)) | M<<2?

不那么精巧,但似乎可以达成目标。MITBBS上有朋友提出了另外几种答案,不过我看不明白。比较典型的利用类似Bit Twiddling Hacks中的技巧的方法是MITBBS的FCer提出来的:(~k)&N | (M<<2),where k = (1<<7)-(1<<2)。不过看不懂为什么k要这样计算。

No comments:

Post a Comment