首页 > 代码库 > HackerRank "Maximizing XOR"
HackerRank "Maximizing XOR"
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"
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。