只保留一个整数的二进制表示的最低位的1,其余全部位设置为0
least_bit.cpp内容如下:
#include <iostream>
using namespace std;
int save_least_bit(int n) { return n ^ (n & (n - 1)); }
int save_least_bit2(int n) { return n & -n;}
int main(int argc, char **argv)
{
const int kRange = 20;
for (int i = 0; i < kRange; ++i)
cout << i << " --> \t" << save_least_bit(i) << "|" << save_least_bit2(i) << endl;
return 0;
}
运行结果如下: