Probability that a N digit number is palindrome
Given an integer N, the task is to find the probability that a number with a number of digits as N is a palindrome.
The number may have leading zeros.
Input: N = 5
Output: 1 / 100
Input: N = 6
Output: 1 / 1000
- As leading zeroes are allowed total number of N digit number is 10N.
- A number is a palindrome when first N/2 digits match with last N/2 digits in reverse order.
- For even number of digits, we can pick first N/2 digits and then duplicate them to form the rest of N/2 digits so we can choose (N)/2 digits.
- For an odd number of digits we can pick first (N-1)/2 digits and then duplicate them to form the rest of (N-1)/2 digits so we can choose (N+1)/2 digits.
- So the probability that an N digit number is palindrome is 10ceil( N / 2 ) / 10N or 1 / 10floor( N / 2 )
Below is the implementation of the approach:
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.