Solution in C#


  • 0
    A

    There is a mathematical way to pick any digit (like index based array or string) from a given number i.e.

    Let the given number is 184372 and if I want to pick digit 4 (at thousandths place), then I can use below expression to pick it

    int x = 184372 ;
    int answer = (x / Math.Pow( 10 , 3)) % 10; // where 3 is the i th place i.e. 100th place of 3 in 372.

    Once you are able to pick any digit from a given number, then you can iterate like a regular string.

    
       public bool IsPalindrome(int x)
            {
                if (x < 0)
                { return false; }
    
                int org = x;
                int cnt = 0;
    
                while (x != 0)
                {
                    x = x / 10;
                    cnt++;
                }
                x = org;
    
    
                int x1 = 0, x2 = 0;
                int y1, y2, y3, y4, y5, y6, y8, y89, y0;
                bool isPal = true;
    
                try
                {
                    checked
                    {
                        //if (cnt % 2 == 0)
                        {
                            for (int i = cnt - 1; i >= cnt / 2; i--)
                            {
                                y1 = int.Parse(Math.Pow(10, i).ToString());
                                y2 = x / y1;
                                x1 = (y2) % 10;
    
                                y6 = cnt - (i + 1);
                                string y7 = Math.Pow(10, (y6)).ToString();
                                y8 = x / int.Parse(y7);
                                x2 = (y8) % 10;
    
                                if (x1 != x2)
                                {
                                    isPal = false;
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    isPal = false;
                }
                return isPal;
            }
        
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.