首页 > 其他 > 详细

HackerRank "Maximizing XOR"

时间:2014-08-28 13:16:19      阅读:265      评论:0      收藏:0      [点我收藏+]

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

HackerRank "Maximizing XOR"

原文:http://www.cnblogs.com/tonix/p/3941322.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!