forked from exercism/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary.java
More file actions
35 lines (26 loc) · 867 Bytes
/
Binary.java
File metadata and controls
35 lines (26 loc) · 867 Bytes
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
public class Binary {
private String binary;
private int decimal;
public Binary(String binary) {
this.binary = binary;
this.decimal = getDecimalFromBinary(binary);
}
public int getDecimal() {
return decimal;
}
private static int getDecimalFromBinary(String binary) {
if (!isValid(binary)) {
return 0;
}
int sum = 0;
for (int i = 0; i < binary.length(); i++) {
sum += Character.getNumericValue(binary.charAt(i)) * (int) Math.pow(2, binary.length() - i - 1);
}
return sum;
}
private static boolean isValid(String binaryRepresentation) {
boolean isValid = binaryRepresentation.chars()
.allMatch(x -> Character.isDigit((char) x) && Character.getNumericValue((char) x) < 2);
return isValid;
}
}