Palindrome

Palindrome ✅

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

public class Palindrome
{
    static void Main(String[] args) {
        int t = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(IsPalindrome(t));
    }
    
    static bool IsPalindrome(int n)
    {
        return n.ToString() == Reverse(n.ToString());
    }

    static string Reverse(string str)
    {
        return new string(str.ToCharArray().Reverse().ToArray());
    }
}

Checking of Palindrome by Comparing first with last position element and so on ...

static bool IsPalindromeByIndex(long n)
{
   	int l = 0;
   	int h = n.ToString().Length - 1;

   	// Keep comparing characters while they are same
   	while (h > l)
   	{
      		if (n.ToString()[l++] != n.ToString()[h--])
      		return false;          
   	}
    	return true;
}         

Checking of Palindrome by Comparing first half with last half portion...

static bool IsPalindrome(long n)
{
       var str = n.ToString();
       if (str.Length % 2 == 0)
       {
           var firstHalf = str.Substring(0, str.Length / 2);
           var secondHalf = Reverse(str.Substring(str.Length / 2));
           if (firstHalf == secondHalf)
               return true;
           return false;
       }
       else
       {
        	var firstHalf = str.Substring(0, str.Length / 2);
            var secondHalf = Reverse(str.Substring((str.Length / 2) + 1));
            if (firstHalf == secondHalf)
                 return true;
            else
                 return false;
       }
}
static string Reverse(string str)
{
    return new string(str.ToCharArray().Reverse().ToArray());
}

Comments

Popular Posts