未设置最右边的设置位 [英] Unset the rightmost set bit
本文介绍了未设置最右边的设置位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能显示的文件:
<一href="http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c">How你设置,清除和切换在C中的单个位?
取出最低位
Possible Duplicates:
How do you set, clear and toggle a single bit in C?
Removing lowest order bit
N
是一个正整数。如何才能最右边的设置位被取消设置?
n
is a positive integer. How can its rightmost set bit be unset?
说 N
= 7
=> N = 0111。
我想 0110
作为输出。有没有什么简单的按位破解来实现这一目标?
Say n
= 7
=> n = 0111.
I want 0110
as the output. Is there any simple bitwise hack to achieve the goal?
推荐答案
尝试 N'放大器; (N-1)
,其中&安培;
是的位与
n = 7
n - 1 =6
n & (n-1)=> 0 1 1 1 (7)
& 0 1 1 0 (6)
---------
0 1 1 0 (done!)
修改(响应由森林给出的评论)
EDIT (in response to the comment given by Forest)
n = 6
n - 1 = 5
n & (n-1)=> 0 1 1 0 (6)
& 0 1 0 1 (5)
---------
0 1 0 0 (done!)
这篇关于未设置最右边的设置位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文