Given a number system with only 3 and 4. Find the nth number in the number system. First few numbers in the number system are: 3, 4, 33, 34, 43, 44, 333, 334, 343, 344, 433, 434, 443, 444, 3333, 3334, 3343, 3344, 3433, 3434, 3443, 3444, …
Source: Zoho Interview
We can generate all numbers with i digits using the numbers with (i-1) digits. The idea is to first add a ‘3’ as prefix in all numbers with (i-1) digit, then add a ‘4’. For example, the numbers with 2 digits are 33, 34, 43 and 44. The numbers with 3 digits are 333, 334, 343, 344, 433, 434, 443 and 444 which can be generated by first adding a 3 as prefix, then 4.
Following are detailed steps.
1) Create an array 'arr' of strings size n+1. 2) Initialize arr as empty string. (Number with 0 digits) 3) Do following while array size is smaller than or equal to n .....a) Generate numbers by adding a 3 as prefix to the numbers generated in previous iteration. Add these numbers to arr .....a) Generate numbers by adding a 4 as prefix to the numbers generated in previous iteration. Add these numbers to arr
Thanks to kaushik Lele for suggesting this idea in a comment here. Following is C++ implementation for the same.
3 4 33 34 43 44 333 334 343 344 433 434 443 444 3333
This article is contributed by Raman. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Write a program to reverse digits of a number
- Program to find whether a no is power of two
- Write an Efficient Method to Check if a Number is Multiple of 3
- Program to find parity
- Write an Efficient C Program to Reverse Bits of a Number
- Minimum number of jumps to reach end
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Print all combinations of points that can compose a given number
- Find Union and Intersection of two unsorted arrays
- Check if a number is multiple of 5 without using / and % operators
- To find sum of two numbers without using any operator
- Find day of the week for a given date
- Given a number, find the next smallest palindrome
- Find the element that appears once