Print numbers in the range 1 to n having bits in alternate pattern | C ++ implementation to print numbers in the range 1 to n having bits in alternate pattern ; function to print numbers in the range 1 to n having bits in alternate pattern ; first number having bits in alternate pattern ; display ; loop until n < curr_num ; generate next number having alternate bit pattern ; if true then break ; display ; generate next number having alternate bit pattern ; if true then break ; display ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printNumHavingAltBitPatrn ( int n ) { int curr_num = 1 ; cout << curr_num << " ▁ " ; while ( 1 ) { curr_num <<= 1 ; if ( n < curr_num ) break ; cout << curr_num << " ▁ " ; curr_num = ( ( curr_num ) << 1 ) ^ 1 ; if ( n < curr_num ) break ; cout << curr_num << " ▁ " ; } } int main ( ) { int n = 50 ; printNumHavingAltBitPatrn ( n ) ; return 0 ; }