Filpping bits in binary number

与世无争的帅哥 提交于 2020-01-07 03:04:18

问题


Can anyone provide a clear logic for the below problem. I am stuck with confusion.

An n bit number is given as input and OP(j) and OP(k) are applied on it one after the other. Objective is to specify how many bits will remain the same after applying these two operations.

OP(i) implies flipping of each ith bit. i > 0


回答1:


Based on your description, the operation OP(i) will change every 'i'th bit, so it changes a total of floor(n / i) bits. Chaining the operation makes things tricky. If the same parameter is passed in twice, then the same values will be flipped, the overall number of flipped bits is 0 since we revert to the original value.

If the second operation uses a different value (j), then you need to add floor(n / j) and then subtract 2*M, where M is the number of common multiples of i and j within the n range. This is because you'll be flipping any common multiples twice and reverting them back to their original value, but having accumulated them twice (once in OP(i) and once in OP(j)), you need to subtract 2 from the total to account for it.




回答2:


For k != j, n-2 bits remains same. When k == j, n-1 bits remains same.



来源:https://stackoverflow.com/questions/33514429/filpping-bits-in-binary-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!