How to determine if a number is palindrome or not in c#
Let us first know what is palindrome
Palindrome is a word, phrase, or sequence that reads the same backwards as forwards, e.g. madam or nurses run,civic,deleveled,level,rotor.
from the definition we can now write the algorithm
1. get the number
2. store the number in a temporary variable
3. reverse the number
4. compare the temporary number with the reversed number if same return palindrome or return not palindrome
the implementation in C#
let use modular programming for this
class program{
static void Main(string[] agrs){
int number;
Console.WriteLine("\n >>> To Find a number is Palindrome or not <<<");
Console.Write("\n Enter a numer");
number=Convert.ToInt32(Console.ReadLine());
var isPalindrome = IsPalindrome(number);
Console.WriteLine(isPalindrome);
Console.ReadLine();
}
public bool IsPalindrome( int number)
{
int remainder;
int sum=0;
int temp;
temp=number;
while (number >0)
{
//get the remainder by dividing with 10
remainder=number % 10;
//get the quotient by diving by 10
number=number/10;
sum = sum * 10 + remainder;}
//test if the original number is equal to the reversed version
if(temp == sum)
{
return true;
}
else{
return false;
}}
}
Comments
Post a Comment