Integers are the numbers whose base value is 10. A binary number is a number expressed in the base-2 numeral. Binary consists of only 2 digits 0 and 1. Two operators are used in the conversion of integers to binary modulo and division to convert the given input into binary numbers.
Input: = 45 Output: = 101101 Input: = 32 Output: = 100000
There are many approaches to convert an integer into binary numbers some of them are discussed here. We will be discussing two of them:
- Using Implementation of Stack
- Using Inbuilt Method- toBinaryString() of the Integer class of Java
Approach 1: Using Implementation of Stack
Actually, the binary number consists of only 0 and 1. To convert an integer to binary divide the number by 2 until it becomes 0. In each step take the modulo by 2 and store the remainder into an array or stack. If we store the remainder into an array then print it into reverse order. If we store the remainder into stack then simply pop one by one element and print it.
Below is the java implementation of the above approach:
Using stack by creating object vector
Approach 2: Using toBinaryString() inbuilt method of the Integer class of Java
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.