mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 17:56:02 +08:00
refactor: BinaryToDecimal
(#5330)
This commit is contained in:
@ -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;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user