Check whether a given number’s binary format is Palindrome or not in C#

I/p: 5

Binary format of 5: 101

Palindrome: True

 

class Binary_Palindrome_Number
{
static void Main(string[] args)
{
ConsoleKeyInfo keyPress;
do
{
Console.WriteLine(“Enter a number:”);
int num = Convert.ToInt32(Console.ReadLine());
string numBinary = num.ConvertToBinary();
bool isPalindrome = CheckPalindromeNUmber(numBinary);
Console.WriteLine(string.Format(“Binary format of given number {0} is {1} and it is {2} Palindrome number.”, num, numBinary, isPalindrome ? “a” : “not a”));
Console.WriteLine(“Press Esc key to exit or any key to continue…”);
keyPress = Console.ReadKey();
}
while (keyPress.Key != ConsoleKey.Escape);
}

private static bool CheckPalindromeNUmber(string num)
{
int start = 0, end = num.Length – 1;
bool flag = true;
while (start <= end)
{
if (!num[start].Equals(num[end]))
{
flag = false;
break;
}
else
{
++start;
–end;
}
}
return flag;
}
}

public static partial class ExtensionMethods
{
public static string ConvertToBinary(this int num)
{
string strBinary = string.Empty;
while (num > 0)
{
strBinary += num % 2;
num = num / 2;
}

return strBinary.ReverseString();
}

public static string ReverseString(this string str)
{
string sb = string.Empty;
for (int i = str.Length – 1; i >= 0; –i)
{
sb += str[i];
}

return sb;
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s