forked from Haresh1204/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bin2Dec.java
33 lines (33 loc) · 907 Bytes
/
Bin2Dec.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.*;
class Bin2Dec
{
public static void main(String arg[])
{
Scanner sc = new Scanner(System.in);
System.out.println("enter binary num to convert it decimal: ");
String a =sc.nextLine();
try
{
System.out.println("decimal of binary num is :"+bin2dec(a));
}
catch(NumberFormatException ex)
{
System.out.println(ex);
}
}
public static int bin2dec(String b) throws NumberFormatException
{
int c =b.length();
int i;
int decimal=0;
for(i=0;i<c;i++)
{
if(b.charAt(i)<'0' || b.charAt(i)>'1')
{
throw new NumberFormatException("please enter valid binary num.");
}
decimal+=((b.charAt(i)-'0') * Math.pow(2,c - i -1) );
}
return decimal;
}
}