ตรวจสอบว่าการแทนค่าบाइनนารีของเลขเป็น Palindrome (อ่านหน้าหลังเหมือนกัน) หรือไม่
ตัวอย่าง: 5 = 101 (Binary) → Palindrome เพราะ 101 อ่านกลับก็ได้ 101
อัลกอริทึม (Bitwise Reverse)
long ReverseBits(long num) {
long rev = 0;
while (num > 0) {
rev <<= 1; // ขยับซ้ายทำที่ว่าง
if ((num & 1) == 1) // ถ้าบิต LSB เป็น 1
rev ^= 1; // ตั้งบิต LSB ของ rev เป็น 1
num >>= 1; // ขยับขวา num
}
return rev;
}
bool IsBinaryPalindrome(long num) {
return num == ReverseBits(num);
}
ตัวอย่างโค้ดเต็ม
using System;
public class Demo {
public static long ReverseBits(long num) {
long rev = 0;
while (num > 0) {
rev <<= 1;
if ((num & 1) == 1) rev ^= 1;
num >>= 1;
}
return rev;
}
public static bool IsBinaryPalindrome(long num) {
return num == ReverseBits(num);
}
public static void Main() {
long num = 5; // Binary: 101
if (IsBinaryPalindrome(num))
Console.WriteLine("Palindrome Number");
else
Console.WriteLine("Not a Palindrome Number");
}
}
ผลลัพธ์
Palindrome Number
ตัวอย่างเพิ่ม: 9 = 1001 (Palindrome), 6 = 110 (Not palindrome)