Count of N-digit Palindrome numbers
Last Updated :
10 Mar, 2022
Given an integer N, the task is to find the count of N-digit Palindrome numbers.
Examples:
Input: N = 1
Output: 9
{1, 2, 3, 4, 5, 6, 7, 8, 9} are all the possible
single digit palindrome numbers.
Input: N = 2
Output: 9
Approach: The first digit can be any of the 9 digits (not 0) and the last digit will have to be same as the first in order for it to be palindrome, the second and the second last digit can be any of the 10 digits and same goes for the rest of the digits. So, for any value of N, the count of N-digit palindromes will be 9 * 10(N – 1) / 2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int nDigitPalindromes( int n)
{
return (9 * pow (10, (n - 1) / 2));
}
int main()
{
int n = 2;
cout << nDigitPalindromes(n);
return 0;
}
|
Java
class GFG
{
static int nDigitPalindromes( int n)
{
return ( 9 * ( int )Math.pow( 10 ,
(n - 1 ) / 2 ));
}
public static void main(String []args)
{
int n = 2 ;
System.out.println(nDigitPalindromes(n));
}
}
|
Python3
def nDigitPalindromes(n) :
return ( 9 * pow ( 10 , (n - 1 ) / / 2 ));
if __name__ = = "__main__" :
n = 2 ;
print (nDigitPalindromes(n));
|
C#
using System;
class GFG
{
static int nDigitPalindromes( int n)
{
return (9 * ( int )Math.Pow(10,
(n - 1) / 2));
}
public static void Main(String []args)
{
int n = 2;
Console.WriteLine(nDigitPalindromes(n));
}
}
|
Javascript
<script>
function nDigitPalindromes(n)
{
return (9 * Math.pow(10, parseInt((n - 1) / 2)));
}
var n = 2;
document.write(nDigitPalindromes(n));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...