Last Updated: 19 Nov, 2020

Sum Of N Digit Palindromes

Easy
Asked in company
Cerner Corporation

Problem statement

You are given an integer 'N'. Your task is to return the sum of all N-digit numbers which are palindrome. A number is said to be palindrome if the number formed by reversing its digits is the same as the given number before.

For Example :

If the value of 'N' is 1, then the answer for this is 45.

Because the list of one-digit numbers is [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ] and each and every number is a palindrome in itself. So our ans equals (1+ 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 0) = 45.
Input Format:
The first line of input contains an integer 'T' number of test cases. 

Each of the next 'T' lines contains a single integer 'N'. 
Output Format :
For each test case print only one line containing an integer representing the sum of N-digit palindromes.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= 'T' <= 50
1 <= 'N' <= 12

Time Limit : 1 sec

Approaches

01 Approach

  1. Initialize the variable 'SUM' = 0.
  2. As all 'N' digit numbers are in the range [10 ^ (N-1), (10^N) - 1] including endpoints.
  3. Traverse each number in this range and check that the current number is palindrome or not. If it’s a palindrome add the current number in the variable 'SUM'.
  4. Return the 'SUM'.

02 Approach

  1. If we observe carefully the sum of ‘N’ digit palindromes is forming a series i.e 45, 495, 49500, 495000, 49500000 i.e  for  ‘N’ = 1 =>  'SUM' = 45, for N = 2 => 'SUM' = 495
  2. Thus we can find this using a mathematical formula as 'SUM' = (99 / 2) * (10^(N -1)) * (10 ^ ((N-1)/2)).
  3. Update the variable 'SUM' by value after the above calculation and return it.