test if binary sum is palindrome in csharp

main.cs
public static bool IsBinarySumPalindrome(int a, int b)
{
    int sum = a + b;
    int originalSum = sum;
    int reversedSum = 0;

    while (sum > 0)
    {
        reversedSum <<= 1; // left shift bitwise operator
        reversedSum |= (sum & 1); // bitwise OR operator with 1

        sum >>= 1; // right shift bitwise operator
    }

    return originalSum == reversedSum;
}
379 chars
17 lines

Explanation:

We define a function IsBinarySumPalindrome that takes in two integers a and b representing binary numbers. We first add a and b to get their sum. We then define two more integers originalSum and reversedSum.

We enter a while loop when the sum value is greater than 0. Within this loop, we first left shift the reversedSum integer by 1 bit position. We then perform a bitwise OR operation with 1 to obtain the last bit of the sum integer, and append it to the reversedSum integer.

We then right shift the sum integer by 1 bit position so that we can obtain the next bit in the next iteration of the while loop. We continue this while loop until the sum integer is reduced to 0.

After the while loop, we compare originalSum and reversedSum. If they are equal, then we have a palindrome binary number for the sum of a and b.

gistlibby LogSnag