【发布时间】:2017-04-20 05:16:37
【问题描述】:
有人问了一个问题:
"用整数n表示,求第二个从0开始的位置 二进制表示中最右边的零位(保证 有这么一点),从右往左数。
返回 2position_of_the_found_bit 的值。”
我写了下面的解决方案,效果很好。
int secondRightmostZeroBit(int n) {
return (int)Math.pow(2,Integer.toBinaryString(n).length()-1-Integer.toBinaryString(n).lastIndexOf('0',Integer.toBinaryString(n).lastIndexOf('0')-1)) ;
}
但下面是我也喜欢的最佳投票解决方案,因为它只有几个字符编码和服务于目的,但我无法理解。有人可以解释一下位操作如何帮助实现它。
int secondRightmostZeroBit(int n) {
return ~(n|(n+1)) & ((n|(n+1))+1) ;
}
【问题讨论】:
标签: java bit-manipulation