跳到正文

算法·理论

Proof process of the Lowbit (x) Function

HuiKuai约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年7月8日
更新
2026年7月8日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

The expression of the lowbit(x)lowbit(x) function is given by lowbit(x)=x&−xlowbit (x)=x \& -x

It is known that for any integer xx be expressed in the form of binary expansion: x=∑i=1N2ki(k1<k2<⋯<kN)x=\sum_{i=1}^{N}2^{k_i}\quad (k_1<k_2<\dots<k_N) where kk is denate the position of the ii-th set bit(i.e.,bit with value 1) in the binary representation ofxx, and NN is the total number of the elements in array kk).For this form,the identity lowbit(x)=2k1lowbit (x)=2^{k_1} always holds.

Why? This is the proof process below.

Let the number MM be the number of digits of the number xx and the array mm be ∁[1,M]∩Zk\complement_{[1,M]\cap\Z}{k}, then let the array yy be ∑i=1M2mi\sum_{i=1}^{M}2^{m_i}.

Because the intersection of xx and yy is empty, y is one’s complement of x,and then yy is equal to ∼x\sim{x}.

According to properties of bitwise AND operation,x&∼x=0x\&\sim x = 0.But if update y to y+1, the result of x&yx\&y will be different, and this is the key to lowbit(x)lowbit(x).

On the one hand, if xx is an odd number and update yy to y+1y+1,the first digit of yy is one, so the result is one, which is equal to 202^0.

On the other hand,if xx is a even number,the first digit of yy is one.Then update yy to y+1y+1,there is a continuous carry occurring on yy until the next one(donate it as k0k_0),whose value is one in xx, of present digit position is zero.After that,this digit position will be one whose value is the same as the number xx‘s.So it is easy to know that the x&y=2k0x\&y=2^{k_0}

Based on above context, we can conclude the function lowbit(x)={1x&1=12k0elselowbit(x) = \begin{cases} 1 & x\&1 = 1 \\ 2^{k_0} & else \end{cases} , which equal to lowbit(x)=x&−x=2kilowbit(x) = x \& -x=2^{k_i}

Thus,the proof is completed.

原文