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