language agnostic - One-liner for checking if integer is of form 2^1-2^j using bitwise operators -
i want 1 line code check whether given integer of form 2i - 2j or not. (using bitwise operators)
as andreyt says, answer can found in hacker's delight:
use following formula turn off rightmost contiguous string of 1-bits (e.g., 01011000 ⇒ 01000000):
((x | (x – 1)) + 1) & xthis may used see if nonnegative integer of form 2j – 2k j ≥ k ≥ 0; apply formula followed 0-test of result.
(was debating whether post this, it's homework question, andreyt mentioned , it's googlable, figure it's more helpful quote directly; i'll let questioner deal ethical implications of accepting on homework, , expect if answer depends on this, write explanation of how works himself)
Comments
Post a Comment