Fast & elegant:
int lsb(int x) {
return x & -x;
}
Tests
int main() {
cout << lsb(2) << "\n"; // 2 = 0010
cout << lsb(4) << "\n"; // 4 = 0100
cout << lsb(6) << "\n"; // 6 = 0110
cout << lsb(7) << "\n"; // 7 = 0111
cout << lsb(8) << "\n"; // 8 = 1000
cout << lsb(12) << "\n"; // 12 = 1100
return 0;
}
Output
2
4
2
1
8
4
Brute force
// x is a signed 32-bit integer
int lsb(int x) {
for (int i = 0; i < 30; i++) {
if (x & (1<<i)) {
return 1 << i;
}
}
return 0;
}
Output for the new version
2
4
2
1
8
4
Practice
Related concepts