refactor: BinaryToDecimal (#5330)

This commit is contained in:
Alex Klymenko
2024-08-16 16:48:47 +02:00
committed by GitHub
parent c20375ae0f
commit e32cab3189
2 changed files with 28 additions and 23 deletions

View File

@ -1,37 +1,33 @@
package com.thealgorithms.conversions;
import java.util.Scanner;
/**
* This class converts a Binary number to a Decimal number
*/
final class BinaryToDecimal {
private static final int BINARY_BASE = 2;
private BinaryToDecimal() {
}
public static long binaryToDecimal(long binNum) {
long binCopy;
long d;
long s = 0;
long power = 0;
binCopy = binNum;
while (binCopy != 0) {
d = binCopy % 10;
s += d * (long) Math.pow(2, power++);
binCopy /= 10;
}
return s;
}
/**
* Main Method
* Converts a binary number to its decimal equivalent.
*
* @param args Command line arguments
* @param binaryNumber The binary number to convert.
* @return The decimal equivalent of the binary number.
* @throws IllegalArgumentException If the binary number contains digits other than 0 and 1.
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Binary number: ");
System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextLong()));
sc.close();
public static long binaryToDecimal(long binaryNumber) {
long decimalValue = 0;
long power = 0;
while (binaryNumber != 0) {
long digit = binaryNumber % 10;
if (digit > 1) {
throw new IllegalArgumentException("Incorrect binary digit: " + digit);
}
decimalValue += (long) (digit * Math.pow(BINARY_BASE, power++));
binaryNumber /= 10;
}
return decimalValue;
}
}