![]() |
VOOZH | about |
Given a positive integer n. The problem is to print numbers in the range 1 to n having first and last bits as the only set bits.
Examples:
Input : n = 10 Output : 1 3 5 9 (1)10 = (1)2. (3)10 = (11)2. (5)10 = (101)2. (9)10 = (1001)2
Naive Approach: Print "1". Now for i = 3 to n, check if (i-1) is a Perfect power of two or not. If true then print i.
Output:
1 3 5 9
Time Complexity : O(n)
Auxiliary Space: O(1)
Efficient Approach: Print "1". Now one by one generate perfect power of two (except '1') with the help of bitwise left shift operation. Bitwise xor these numbers with 1 and if result is in the range print them else stop.
Output:
1 3 5 9
Time Complexity : O(logn)
Auxiliary Space: O(1)