标签:style blog color io strong ar for art div
A natural thought is brutal-force. But as you may have already thought of, there must be a smarter one. And yes there is.
Think like this: XOR gives you all different bits, if you could imagine the binary representation of L^R, it can be represented as: 1XXXXX... What is asked is the ‘maximum‘ value of L^R - and that means 1111111... so this maximum value only depends on which is the highest 1 - it is irrelevant with all intermediate values. So now the question turns to be: which is the highest bit of (L^R)?
Then an more elegant solution comes:
int maxXor(int l, int r) { size_t bitLen = floor(log(l^r)/log(2)); return (2 << bitLen) - 1; }
Lesson learnt: make bit operations meaningful
标签:style blog color io strong ar for art div
原文地址:http://www.cnblogs.com/tonix/p/3941322.html