mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-11 14:12:36 +08:00
Add test case for BinaryToDecimal (#3684)
This commit is contained in:
@ -7,6 +7,17 @@ import java.util.Scanner;
|
|||||||
*/
|
*/
|
||||||
class BinaryToDecimal {
|
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
|
* Main Method
|
||||||
*
|
*
|
||||||
@ -14,16 +25,8 @@ class BinaryToDecimal {
|
|||||||
*/
|
*/
|
||||||
public static void main(String args[]) {
|
public static void main(String args[]) {
|
||||||
Scanner sc = new Scanner(System.in);
|
Scanner sc = new Scanner(System.in);
|
||||||
int binNum, binCopy, d, s = 0, power = 0;
|
|
||||||
System.out.print("Binary number: ");
|
System.out.print("Binary number: ");
|
||||||
binNum = sc.nextInt();
|
System.out.println("Decimal equivalent:" + binaryToDecimal(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);
|
|
||||||
sc.close();
|
sc.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.thealgorithms.conversions;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class BinaryToDecimalTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testBinaryToDecimal() {
|
||||||
|
//zeros at the starting should be removed
|
||||||
|
assertEquals(0, BinaryToDecimal.binaryToDecimal(0));
|
||||||
|
assertEquals(1, BinaryToDecimal.binaryToDecimal(1));
|
||||||
|
assertEquals(5, BinaryToDecimal.binaryToDecimal(101));
|
||||||
|
assertEquals(63, BinaryToDecimal.binaryToDecimal(111111));
|
||||||
|
assertEquals(512, BinaryToDecimal.binaryToDecimal(1000000000));
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user