package com.JavaInterview.Programs;
import java.util.*;
/**
* Find Out Factorial of a number
*
* @author:http://javainterviewprograms.blogspot.in/
*
*/
public class BinaryToDecimal {
/*Convert Binary to decimal */
public int toDecimal(int binary) {
/**if you take input binary number as string
then while fetching string.charAt(index)
* and type cast to integer -> it
will give ASCII value of that char(0=48 & 1=49) and
* it will cause result to differ from
original decimal value **/
int decimalNumber = 0;
int power = 0;
while (binary > 0) {
int tmp = binary % 10;
decimalNumber += tmp * Math.pow(2, power);
binary = binary / 10;
power++;
}
return decimalNumber;
}
/*To Check if number is binary or not*/
public boolean isBinary(int binary)
{
boolean status=true;
while(true)
{
if(binary==0)
{
break ;
}
else
{
int tmp=binary%10;
if(tmp>1)
{
status =false;
break;
}
binary=binary/10;
}
}
return status;
}
public static void main(String args[]) {
BinaryToDecimal B2D = new BinaryToDecimal();
Scanner input = new Scanner(System.in);
System.out.println("Please enter Binary
Number");
int bNumber = input.nextInt();
if(B2D.isBinary(bNumber))
{
System.out.println(bNumber + " to
Decimal :" + B2D.toDecimal(bNumber));
}
else
{
System.out.println("It's not a Binary
Number ");
}
}
}
Output:
Please enter
Binary Number
1011
1011 to
Decimal :11
No comments:
Post a Comment