码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank "Maximizing XOR"

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

标签: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

HackerRank "Maximizing XOR"

标签:style   blog   color   io   strong   ar   for   art   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!