Convert Binary to Decimal number in Java. OR
Write a program to convert Binary to Decimal number in Java.
Given a Binary number, Convert it to Decimal number. Lets see what is the input and expected output.
Algorithm
Converting Binary to Decimal number is very easy,
Similar posts:
- Compress a given string in-place and with constant extra space.
- Check whether a given string is an interleaving of String 1 and String 2.
- Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord.
- Serialize and Deserialize a Binary Tree
- Advanced Multithreading Interview Questions In Java
Step 1: Get the Right most bit and check whether it is set or not.
For getting the Right most bit, Mod the number by 10. (number % 10).
Step 2:
If the Right most bit is set, then get the corresponding value of that position using the formula
Math.pow(2, indexPosition) and add it to variable sum.
If the Right most bit is not set, then no need to do anything and no value will be added to variable sum.
Step 3: After the Right most bit is checked, Divide the number by 10 to get the remaining number for next iteration. Also Increment indexPosition.
(number/10) and indexPosition++.
Continue until number is > 0.
Convert Binary to Decimal number in Java.
package javabypatel; public class ConvertBinaryToDecimal { public static void main(String[] args) { System.out.println(binaryToInt(101)); } public static int binaryToInt(int number){ int index = 0; int sum = 0; while (number > 0){ int lastBit = number % 10; //Get last bit of binary number sum += Math.pow(2, index) * lastBit; //sum all corresponding position value. //lastBit will be either 1 or 0 as it is binary number, so if bit is not set that is 0, then that value will be 0. //If bit is set that is 1, then we sum value of corresponding position using Math.pow(2, index). number = number/10; //we already checked last bit above, so discard it in next iteration. index++; //Increment index for next position. } return sum; } }
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
No comments:
Post a Comment