CC-15 : Generate N binary numbers using a Queue.
Description:
Generate N binary numbers using a Queue.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| QueueGenerateBinary queue= new QueueGenerateBinary(); queue.queueGenerateBinary(7); |
7 binary numbers starting from 1 are: 1 10 11 100 101 110 111 |
Pseudocode:
| Declare and initialize a Queue of Strings to hold the generated binary numbers. |
| In Queue add the String “1”. |
| We need to generated N binary numbers so use a for loop to iterate from 0 to N-1:
Remove current first node String currBin from Queue holding binary numbers.
Append “0”to String currBin removed from Queue above and push it into the end of Queue again.
Append “1”to String currBin removed from Queue above and push it into the end of Queue again.
|
Code:
public void queueGenerateBinary(int numBins) throws Exception {
Queue<String> queue=new LinkedList<String>();
queue.add("1");
String currBin;
System.out.println(numBins+" binary numbers starting from 1 are:");
for(int idx=0; idx < numBins;idx++) {
currBin=(String) queue.remove();
System.out.println(currBin);
queue.add(currBin+"0");
queue.add(currBin+"1");
}
return;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |