Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

posted on 2014-08-28 12:02  Tonix  阅读(262)  评论(0编辑  收藏  举报