long long NumberOfA(long long x) { long long t = x <<1; while(t^(t&-t)) t ^= (t&-t); return t-++x; } long long x = 10000000000; printf("%lld ==> %lld\n", 10LL, NumberOfA(10LL) ); printf("%lld ==> %lld\n", x, NumberOfA(x) );
Output
10 ==> 5 10000000000 ==> 7179869183
Link to IDEOne code
Trying to explain logic (using example 10 or 1010b )
- Shift x left 1. (Value 20 or
10100b ) - Disable all low bits, leaving only the high bit (value 16 or
10000b ) - Subtract x + 1 (
16 - 11 == 5 )
Attempt to explain(although its not easy)
Your rule is that a ^ x must be greater than x , but you cannot add extra bits to a or x .
(If you start with a 4-bit value, you can only use 4-bit)
The largest possible value for a number in N bits is 2^n -1 .
(e.g. 4-bit number, 2 ^ 4-1 == 15)
Lets call this number B.
Between your x and B value (inclusive), B - x possible values ββare possible.
(back to my example, 10. Between 15 and 10 there are 5 possible values: 11 , 12 , 13 , 14 , 15 )
In my code t there is x << 1 , then when turning off all the least significant bits.
( 10 << 1 - 20 ; turn off all the low bits to get 16 )
Then 16 - 1 B , and B - x is your answer:
( t - 1 - x, matches t - ++x , is the answer)
source share