Home > Backend Development > C++ > An interesting way to generate binary numbers from 1 to n?

An interesting way to generate binary numbers from 1 to n?

PHPz
Release: 2023-09-11 21:09:02
forward
1027 people have browsed it

An interesting way to generate binary numbers from 1 to n?

Here we will see an interesting method for generating binary numbers from 1 to n. We do this using queues. Initially, the first binary number '1' will be held in the queue. Now repeatedly remove the element from the queue and print it and add 0 to the end of the previous element and 1 to the end of the previous element and insert them into the queue. Let's look at the algorithm to get this idea.

Algorithm

genBinaryNumbers(n)

Begin
   define empty queue.
   insert 1 into the queue
   while n is not 0, do
      delete element from queue and store it into s1
      print s1
      s2 := s1
      insert s1 by adding 0 after it into queue
      insert s1 by adding 1 after it into queue
      decrease n by 1
   done
End
Copy after login

Example

’s Chinese translation is:

Example

#include <iostream>
#include <queue>
using namespace std;
void genBinaryNumbers(int n){
   queue<string> qu;
   qu.push("1");
   while(n != 0){
      string s1 = qu.front();
      qu.pop();
      cout << s1 << " ";
      string s2 = s1;
      qu.push(s1 + "0");
      qu.push(s1 + "1");
      n--;
   }
}
int main() {
   int n = 15;
   genBinaryNumbers(n);
}
Copy after login

Output

1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
Copy after login

The above is the detailed content of An interesting way to generate binary numbers from 1 to n?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template