Hacker News new | past | comments | ask | show | jobs | submit login

Another quick way that doesn’t rely on builtins is x && !(x & (x - 1)).



I'd first ask the interviewer whether they're ok with a function is_zero_or_two_power...


Isn't that what the "x &&" is for? For x = 0, (x - 1) is 0xffffffff, x & (x-1) is 0, !(x & (x-1)) is 1, and x && !(x & (x-1)) is 0.


Yes, that's exactly what it's for. The answer I hope for is that they don't care about the case of x==0, so that I can leave out the "x &&" part, leaving the noticeably simpler answer

(x & x-1) == 0




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: