ที่นี่เราจะเห็นวิธีการหนึ่งที่น่าสนใจในการสร้างเลขฐานสองจาก 1 ถึง n ที่นี่เราใช้คิว เริ่มแรกคิวจะเก็บเลขฐานสองตัวแรกเป็น '1' ตอนนี้ลบองค์ประกอบออกจากคิวซ้ำแล้วซ้ำอีก และพิมพ์ และเพิ่ม 0 ต่อท้ายรายการส่วนหน้า และต่อท้าย 1 เมื่อสิ้นสุดเวลาส่วนหน้า และแทรกลงในคิว ให้เราดูอัลกอริทึมเพื่อให้ได้แนวคิด
อัลกอริทึม
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
ตัวอย่าง
#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);
} ผลลัพธ์
1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111