How to find out all palindromic numbers

后端 未结 8 1808
独厮守ぢ
独厮守ぢ 2020-12-14 12:05

A palindromic number or numeral palindrome is a \"symmetrical\" number like 16461, that remains the same when its digits are reversed.

The term palindromic is derive

相关标签:
8条回答
  • 2020-12-14 12:41

    I wrote these methods in C# which may be of some help. The main method builds a definitive list of all palindromic numbers up to the given number of digits. Its fast and commented throughout to help explain the processes I have used.

    I've also included some support methods including a fast palindromic test and its worth pointing out that pow10[x] is an array of the powers of 10 to further improve speed.

                        lhs *= 10;
                        rhs /= 10;
                    }
                    palindrome = MathExt.Concat( lhs * 10, MathExt.ReverseDigits( rhs ) );      // Multiplying the lhs by 10 is equivalent to adding b == 0
                    result.Add( palindrome );       // Add numbers of the form aaa + 0 + aaa
    
                    lhs = a;
                    for ( ulong b = 1; b != 10; b++ )
                    {
                        rhs = a * 10 + b; // Adding b before we reverse guarantees that there is no trailing 0s
                        palindrome = MathExt.Concat( lhs, MathExt.ReverseDigits( rhs ) );       // Works except when b == 0
                        result.Add( palindrome );       // Add numbers of the form aaa + b + aaa
                    }
                    a++;
                }
                pow *= 10;        // Each pass of the outer loop add an extra digit to aaa
            } 
            return (result);
        }
    
    
        /// <summary>
        ///  Reverses the digits in a number returning it as a new number. Trailing '0's will be lost.
        /// </summary>
        /// <param name="n">The number to reverse.</param>
        /// <param name="radix">The radix or base of the number to reverse.</param>
        /// <returns>The reversed number.</returns>
        static public ulong ReverseDigits( ulong n, uint radix = 10 )
        {
            // Reverse the number
            ulong result = 0;
            do
            {
                // Extract the least significant digit using standard modular arithmetric
                result *= radix;
                result += n % radix;
                n /= radix;
            } while ( n != 0 );
            return (result);
        }
    
    
    /// <summary>
        /// Concaternates the specified numbers 'a' and 'b' forming a new number 'ab'.
        /// </summary>
        /// <example>If a = 1234 and b = 5678 then Concat(a,b) = 12345678.</example>
        /// <param name="a">The first number.</param>
        /// <param name="b">The second number.</param>
        /// <returns>The concaternated number 'ab'.</returns>
        public static ulong Concat( this ulong a, ulong b )
        {
            // Concaternate the two numbers by shifting 'a' to the left by the number of digits in 'b' and then adding 'b'
            return (a * pow10[NumberOfDigits( b )] + b);
        }
    
        /// <summary>
        /// Evaluate whether the passed integer is a palindrome in base 10 or not.
        /// </summary>
        /// <param name="n">Integer to test.</param>
        /// <returns>True - Palindrome, False - Non palindrome.</returns>
        static public bool IsPalindrome( this ulong n )
        {
            uint divisor = NumberOfDigits( n ) - 1;
            do
            {
                // Extract the most and least significant digits of (n)
                ulong msd = n / pow10[divisor];
                ulong lsd = n % 10;
    
                // Check they match!
                if ( msd != lsd )
                    return (false);
    
                // Remove the msd and lsd from (n) and test the next most and least significant digits.
                n -= msd * pow10[divisor];  // Remove msd
                n /= 10;                    // Remove lsd
                divisor -= 2;               // Number has reduced in size by 2 digits 
            } while ( n != 0 );
            return (true);
        }
    
    0 讨论(0)
  • 2020-12-14 12:47
    import Queue
    import copy
    
    def printPalindromesTillK(K):
        q = Queue.Queue(K);
        for i in range(0, 10):
            q.put(str(i));
            q.put(str(i) + str(i));
        while(not q.empty()):
            elem = q.get();
            print  elem;
            for i in range(1, 10):
                item = str(i) + elem + str(i);
                if int(item) <= K:
                   q.put(item); 
    
    print printPalindromesTillK(10000);
    
    0 讨论(0)
提交回复
热议问题