mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 17:56:02 +08:00
Add test case for BinaryToDecimal (#3684)
This commit is contained in:
@ -7,6 +7,17 @@ import java.util.Scanner;
|
||||
*/
|
||||
class BinaryToDecimal {
|
||||
|
||||
public static int binaryToDecimal(int binNum) {
|
||||
int binCopy, d, s = 0, power = 0;
|
||||
binCopy = binNum;
|
||||
while (binCopy != 0) {
|
||||
d = binCopy % 10;
|
||||
s += d * (int) Math.pow(2, power++);
|
||||
binCopy /= 10;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
@ -14,16 +25,8 @@ class BinaryToDecimal {
|
||||
*/
|
||||
public static void main(String args[]) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int binNum, binCopy, d, s = 0, power = 0;
|
||||
System.out.print("Binary number: ");
|
||||
binNum = sc.nextInt();
|
||||
binCopy = binNum;
|
||||
while (binCopy != 0) {
|
||||
d = binCopy % 10;
|
||||
s += d * (int) Math.pow(2, power++);
|
||||
binCopy /= 10;
|
||||
}
|
||||
System.out.println("Decimal equivalent:" + s);
|
||||
System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextInt()));
|
||||
sc.close();
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user