📜  N位最小和最大回文

📅  最后修改于: 2021-04-23 17:52:36             🧑  作者: Mango

给定数字N。任务是找到N位数可能出现的最小和最大回文数。
例子:

Input: N = 4 
Output: 
Smallest Palindrome = 1001
Largest Palindrome = 9999

Input: N = 5
Output: 
Smallest Palindrome = 10001
Largest Palindrome = 99999

最小的N位回文数:仔细观察,您会发现对于N = 1,最小的回文数将为0。对于其他任何N值,最小的回文数的第一位和最后一位均为1。之间的数字为0。

  • 情况1:如果N = 1,则答案将为0。
  • 情况2:如果N!= 1,则答案将是(10 (N-1) )+ 1。

最大的N位回文数:与上述方法类似,您可以看到,通过在N上附加9,可以获得具有N位的最大回文数。因此,最大的N位回文数将为10 N – 1
下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
using namespace std;
 
// Function to print the smallest and largest
// palindrome with N digits
void printPalindrome(int n)
{
    if (n == 1)
    {
        cout<<"Smallest Palindrome: 0"<


Java
// Java implementation of the above approach
class GfG {
 
    // Function to print the smallest and largest
    // palindrome with N digits
    static void printPalindrome(int n)
    {
        if (n == 1)
        {
            System.out.println("Smallest Palindrome: 0");
            System.out.println("Largest Palindrome: 9");
        }
        else
        {
            System.out.println("Smallest Palindrome: "
                    + (int)(Math.pow(10, n - 1)) + 1);
                     
            System.out.println("Largest Palindrome: "
                    + ((int)(Math.pow(10,n)) - 1));
        }
    }
     
    // Driver Code
    public static void main(String[] args) {
        int n = 4;
        printPalindrome(n);
    }
}


Python3
# Python 3 implementation of the above approach
 
from math import pow
 
# Function to print the smallest and largest
# palindrome with N digits
def printPalindrome(n):
    if (n == 1):
        print("Smallest Palindrome: 0")
        print("Largest Palindrome: 9")
    else:
        print("Smallest Palindrome:", int(pow(10, n - 1))+1)
        print("Largest Palindrome:", int(pow(10,n))-1)
     
 
# Driver Code
if __name__ == '__main__':
    n = 4
    printPalindrome(n)
 
# This code is contributed by
# Surendra_Gangwar


C#
// C# implementation of the approach
using System;
 
class GfG
{
 
    // Function to print the smallest and largest
    // palindrome with N digits
    static void printPalindrome(int n)
    {
        if (n == 1)
        {
            Console.WriteLine("Smallest Palindrome: 0");
            Console.WriteLine("Largest Palindrome: 9");
        }
        else
        {
            Console.WriteLine("Smallest Palindrome: "
                    + (int)(Math.Pow(10, n - 1)) + 1);
                     
            Console.WriteLine("Largest Palindrome: "
                    + ((int)(Math.Pow(10,n)) - 1));
        }
    }
     
    // Driver Code
    public static void Main(String[] args)
    {
        int n = 4;
        printPalindrome(n);
    }
}
 
/* This code contributed by PrinciRaj1992 */


PHP


Javascript


输出:
Smallest Palindrome: 1001
Largest Palindrome: 9999

时间复杂度: O(1)