![]() |
You are given a binary number as input and your task is to convert that number to its decimal equivalent through a Java program. Examples : Input : 1100 Methods for Binary to Decimal ConversionsThere are certain methods used for Binary to Decimal Conversions mentioned below:
1. Basic Approach for Binary to Decimal ConversionSo the basic idea for converting a binary number to its decimal equivalent is to multiply each digit in the binary number by 2 raised to the power of its positional value and then add up these values. For example :
Below is a Java Code for the above-mentioned approach (Works both for String as well as integer Data Type ): We have used here switch case for different input types( i.e. String or integer ). Users have to enter their choice of input. The given choice will execute/call their respective function. Below is the implementation of the above method:Java
Output
Decimal Equivalent of 1010 is = 10 Decimal Equivalent of 1100 is = 12 Complexity of the above method:
Here n is total number of digits in the given binary number. If you are dealing with large binary value , try to use ‘long’ instead of ‘int’ to avoid any errors. 2. Using pre-defined functionInstead of the approach we can directly use a Java built-in method (i.e. Integer.parseInt()) that converts a string representation of an integer to its actual integer value. Below is the implementation of the above method:Java
Output
Decimal Equivalent of 1010 is 10 Complexity of the above method:
Here n is total number of digits in the given binary number. If you are dealing with large binary value , try to use ‘long’ instead of ‘int’ to avoid any errors. 3. Using Bitwise operatorsWe can also use << to perform the above operations. The >> operator in Java is the right shift operator. It shifts the bits of a number to the right by a specified number of positions. This operator generally means : x>>y = x/2^y
Below shown a Java Code for the above mentioned approach : Java
Output :Enter the Binary number : 1100 Complexity of the above method:
Here n is total number of digits in the given binary number. |
Reffered: https://www.geeksforgeeks.org
Java Programs |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |