Problem
Compute the parity of a long integer.
Solution
- Erases the least significant bit of a number
e.g 1111 -> 1111 & 1110 = 1110
1110 -> 1110 & 1101 = 1100
1101 -> 1101 & 1100 = 1100
1100 -> 1100 & 1011 = 1000
1011 -> 1011 & 1010 = 1010
1010 -> 1010 & 1001 = 1000
using System;
namespace ComputerParity
{
class Program
{
static bool IsOddParity(long num)
{
int count = 0;
while (num != 0)
{
count ^= 1;
num = num & (num - 1);
}
return (count == 0) ? true : false;
}
static void Main(string[] args)
{
for (long i = 0; i < 60; i++)
{
Console.WriteLine("{0} {1, 10}, {2, 10}", i.ToString("X10"), i, Program.IsOddParity(i));
}
}
}
}
Output
0000000000 0, False
0000000001 1, True
0000000002 2, True
0000000003 3, False
0000000004 4, True
0000000005 5, False
0000000006 6, False
0000000007 7, True
0000000008 8, True
0000000009 9, False
000000000A 10, False
000000000B 11, True
000000000C 12, False
000000000D 13, True
000000000E 14, True
000000000F 15, False
0000000010 16, True
0000000011 17, False
0000000012 18, False
0000000013 19, True
0000000014 20, False
0000000015 21, True
0000000016 22, True
0000000017 23, False
0000000018 24, False
0000000019 25, True
000000001A 26, True
000000001B 27, False
000000001C 28, True
000000001D 29, False
000000001E 30, False
000000001F 31, True
0000000020 32, True
0000000021 33, False
0000000022 34, False
0000000023 35, True
0000000024 36, False
0000000025 37, True
0000000026 38, True
0000000027 39, False
0000000028 40, False
0000000029 41, True
000000002A 42, True
000000002B 43, False
000000002C 44, True
000000002D 45, False
000000002E 46, False
000000002F 47, True
0000000030 48, False
0000000031 49, True
0000000032 50, True
0000000033 51, False
0000000034 52, True
0000000035 53, False
0000000036 54, False
0000000037 55, True
0000000038 56, True
0000000039 57, False
000000003A 58, False
000000003B 59, True
Press any key to continue . . .