Find the first N pure numbers
Given an integer N, the task is to print first Nth pure numbers. A number is said to be pure if
- It has even number of digits.
- All the digits are either 4 or 5.
- And the number is a palindrome.
First few pure numbers are 44, 55, 4444, 4554, 5445, 5555, …
Input: N = 4
Output: 44 55 4444 5445
Input: N = 10
Output: 44 55 4444 4554 5445 5555 444444 454454 544445 554455
Approach: The idea is similar to the approach discussed here. At each step of the queue we can generate the next number by adding 4 and 5 on both of the sides i.e. the ending and the beginning of the previous number:
q.push("4" + temp + "4"); q.push("5" + temp + "5");
Proceeding in this way we can take care of palindromes and even length numbers
Below is the implementation of the above approach:
44 55 4444 5445
Approach 2: The approach divides the even palindromic number into two equal parts, both of which mirror each other. The idea is to build the first part using the same approach that is used to build a binary counter by flipping every second bit; except, instead of flipping 0 and 1, we’re flipping 4 and 5. Later, we use the first part of the number and the palindromic property to create the final pure number.
44, 55, 4444, 4554... can be separated out into 4 | 4 5 | 5 44 | 44 45 | 54 54 | 45 55 | 55
The numbers mimic the property of binary numbers of first ‘k’ bits where k = 1, 2, 3 and so on.
0 1 00 01 10 11
So, we start by flipping the last bit after every iteration, then moving to the (k-1) bit which is flipped after every 2 iterations and so on. The first time, it will be flipped n times and the next, it will be flipped n/2 times and so on.
Since n is a sum of all possible numbers with k bits where k= 1, 2, 3…, our number will be a sum of 2 + 4 + 8 + …2k numbers. We consecutively divide n by 2 and stop if its value is equal to zero as there will be no further bits required to be added and also because, in the next iteration, the number will be flipped after twice the number of elements it took in the previous iteration.
We can use a stack to store the values and then pop them out in sequential order, or by storing the data in a string and simply reversing it, which uses less space than a stack does.
44 55 4444 4554 5445 5555 444444 445544 454454 455554
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.