I want a one line code to check whether a given integer is of form 2i - 2开发者_StackOverflow社区j or NOT. (using bitwise operators)
As AndreyT says, the answer can be found in Hacker's Delight:
Use the following formula to turn off the rightmost contiguous string of 1-bits (e.g., 01011000 ⇒ 01000000):
((x | (x – 1)) + 1) & x
This may be used to see if a nonnegative integer is of the form 2j – 2k for some j ≥ k ≥ 0; apply the formula followed by a 0-test of the result.
(was debating whether to post this, as it's a homework question, but as AndreyT already mentioned it and it's easily Googlable, I figure it's more helpful to quote directly; I'll let the questioner deal with the ethical implications of accepting help on the homework, and I expect that if his answer depends on this, he will write up the explanation of how it works himself)
A hint or two:
Other have pointed out that what you're looking for is a number that consists of a string of ones followed by a string of zeros.
If you flip all the bits in this, you'll get a string of 0's followed by a string of 1's. If you increment that, all the one bits will become zeros, and exactly one bit above those will become a one.
If you AND those last two together, you'll get zero.
In binary, a power of two is a number of the form 100...0
(A 1
followed by x
0
s, where x
is the exponent)
Therefore, any binary number of the form 2i - 2j will be a string of 1
s followed by a string of 0
s.
Windows Calculator (in binary mode) is a great way to experiment with this.
Let's take a look at this for a moment. If i=j, then the answer is checking to see if the integer is 0. Otherwise, the key is to see how often the bits toggle I think as what you want to see is if all the 1s are together as a group, collectively, as really the arithmetic here is quite simple. If the toggle is 2 then it is of that form.
Left shift until you get a 0, once u get a zero, u should not get 1 again
精彩评论