Java Program to Convert a Decimal Number to Binary & Count the Number of 1s
As per the number system, default computations are carried over decimal numbers whose base is standardized as 10. Machine computes all the execution at the physical layer in 0s and 1s. So arises a need for a number system with base 2 known as a binary number system. A binary number can be converted to a decimal number and vice versa. In java there are 4 types of numbers:
|Types Of Numbers||Base|
Approaches: In Java, there are 2 ways to convert either using pre-defined methods or third-grade logic building as listed below:
- Using Integer.toBinaryString method (Integer wrapper class)
- Using the Brute force method (without any use of predefined classes)
Input. 1: 10 Output 1: The binary equivalent of 10 is : 1010 Number of 1s is : 2 Input 2: 15 Output 2: The binary equivalent of 15 is : 1111 Number of 1s is 4
Approach 1: Using toBinaryString() Method: represents the number to be converted into binary. The Integer class of java provides some useful methods to deal with Integers. One such method is Integer.toBinaryString(int x)
public static String toBinaryString(int variable_name)
Parameters: Decimal integer to be converted.
Return Type: String which is holding binary representation of the integer converted or simply binary equivalent of integer as a String object.
Exceptions: There are no exceptions thrown by this method
Parameter: It takes one parameter of type Integer (or int)
Implementation: To count the number of 1s, check if each character of the obtained binary string equals 1 or not.
The binary equivalent of 18 is : 10010 Number of 1s is : 2
Approach 2:Without using pre-defined variables
- Dividing the decimal number by 2 which is to be converted into binary
- Storing the remainder
The binary equivalent of 18 is : 01001 Number of 1s is : 2