ตรวจสอบว่าการแทนค่าฐานสองของเลขมีบิต 1 ติดกัน (adjacent set bits) หรือไม่
ตัวอย่าง: 12 = 1100₂ มีบิต 1 ติดกัน
วิธี: Shift ขวา 1 บิต แล้ว AND กับตัวเดิม ถ้าผลลัพธ์ ≠ 0 → มีบิต 1 ติดกัน
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
bool hasConsecutiveOnes(int n) {
return ((n & (n >> 1)) != 0);
}
int main() {
int num = 67; // 1000011
if (hasConsecutiveOnes(num)) cout << "Has Consecutive 1s";
else cout << "Has No Consecutive 1s";
}
ผลลัพธ์
Has Consecutive 1s