Skip to content

Latest commit

 

History

History
36 lines (29 loc) · 852 Bytes

generate-binary-numbers.md

File metadata and controls

36 lines (29 loc) · 852 Bytes

Generate Binary Numbers

Problem Link

Given a number N. The task is to generate and print all binary numbers with decimal values from 1 to N.

Sample Input

2

Sample Output

1
10

Solution

vector<string> generate(int N) {
    vector<string> ans(N);

	for(int i = 1; i <= N; ++i) {
	    int num = i;
	    while(num) {
	        ans[i - 1] += (char) ('0' + (num & 1));
	        num >>= 1;
	    }
	    reverse(ans[i - 1].begin(), ans[i - 1].end());
	}

	return ans;
}

Accepted

image