Java Program to Generate Binary NumbersIn this section, we will create Java programs that generates binary numbers from the specified range (0 to n). The generation of binary numbers from 1 to n can be achieved through a binary tree. We know that in a tree, every node has two child nodes i.e. right and left nodes. In this binary tree the root node will be 1. In order to get the left and right node of the root node, we will append 0 and 1 respectively at the end of the root node, and so on. Consider the following binary tree for the same. Let's follow the steps given below to generate the binary numbers.
Implement the above approach in a Java program. GenerateBinaryNumbers.java Output: 1 10 11 100 101 110 111 1 10 11 100 101 110 111 1000 1001 1010 Let's see another logic for the same. Run a loop from 1 to n. Inside the loop, invoke decimal to binary conversion.
The time and space complexity for the following solution is O(n). Java Program to Generate Binary Numbers Up to nUsing QueueGenerateBinaryNumbers.java Output: 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 Let's see another logic. In the following Java program, we have not used any data structure. Instead we have used a function itoa(). The function converts integer into null-terminated string. It can convert negative numbers too.
GenerateBinaryNumbers.java Output: 0 1 10 11 100 101 110 111 1000 1001 1010 Next TopicLongest Odd-Even Subsequence in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India