-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryToDecimal.java
36 lines (27 loc) · 1.1 KB
/
BinaryToDecimal.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
34
35
36
import java.util.Scanner;
public class BinaryToDecimal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input binary number from the user
System.out.print("Enter a binary number: ");
String binaryString = scanner.nextLine();
// Convert binary to decimal
int decimal = binaryToDecimal(binaryString);
// Display the result
System.out.println("Decimal equivalent: " + decimal);
scanner.close();
}
public static int binaryToDecimal(String binaryString) {
int decimal = 0;
int power = 0;
// Iterate over each character of the binary string starting from the rightmost
for (int i = binaryString.length() - 1; i >= 0; i--) {
// Convert character to integer
int digit = Character.getNumericValue(binaryString.charAt(i));
// Update decimal using the formula: decimal += digit * 2^power
decimal += digit * Math.pow(2, power);
power++;
}
return decimal;
}
}