Project Euler #4: Largest palindrome product

  • + 0 comments

    using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static void Main(String[] args) { int T = Convert.ToInt32(Console.ReadLine()); for (int a0 = 0; a0 < T; a0++) { int n = Convert.ToInt32(Console.ReadLine()); int largestPalindrome = FindLargestPalindrome(n); Console.WriteLine(largestPalindrome); } }

    static bool IsPalindrome(int num) { string numStr = num.ToString(); int len = numStr.Length; int left =0; int right =len-1;

    for(int i=0 ; i<=len/2 ; i++)
    {
        if(numStr[left]==numStr[right])
        {
            left++;
            right--;
        }
        else
        {return false;}
    }
    
    // for (int i = 0; i < len / 2; i++) {
    //     if (numStr[i] != numStr[len - 1 - i]) {
    //         return false;
    //     }
    // }
    
    /*
    while(left<right)
    {
        if(numStr[left]!=numStr[right])
        {
            return false;
            break;
        }
        left++;
        right--;
    }
    */
    return true;
    

    }

    static int FindLargestPalindrome(int n) { for (int i = n - 1; i >= 101101; i--) { if (IsPalindrome(i)) { for (int j = 100; j <= 999; j++) { if (i % j == 0 && i / j >= 100 && i / j <= 999) { return i; } } } } return -1; // If no palindrome is found } }