File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ apply plugin : " java"
2+ apply plugin : " eclipse"
3+ apply plugin : " idea"
4+
5+ repositories {
6+ mavenCentral()
7+ }
8+
9+ dependencies {
10+ testCompile " junit:junit:4.10"
11+ }
Original file line number Diff line number Diff line change 1+ public class Binary {
2+
3+ private String binary ;
4+ private int decimal ;
5+
6+ public Binary (String binary ) {
7+ this .binary = binary ;
8+ this .decimal = getDecimalFromBinary (binary );
9+ }
10+
11+ public int getDecimal () {
12+ return decimal ;
13+ }
14+
15+ private static int getDecimalFromBinary (String binary ) {
16+ if (!isValid (binary )) {
17+ return 0 ;
18+ }
19+
20+ int sum = 0 ;
21+
22+ for (int i = 0 ; i < binary .length (); i ++) {
23+ sum += Character .getNumericValue (binary .charAt (i )) * (int ) Math .pow (2 , binary .length () - i - 1 );
24+ }
25+
26+ return sum ;
27+ }
28+
29+ private static boolean isValid (String binaryRepresentation ) {
30+ boolean isValid = binaryRepresentation .chars ()
31+ .allMatch (x -> Character .isDigit ((char ) x ) && Character .getNumericValue ((char ) x ) < 2 );
32+
33+ return isValid ;
34+ }
35+ }
Original file line number Diff line number Diff line change 1+ public class Binary {
2+ }
Original file line number Diff line number Diff line change 1+ import org .junit .Test ;
2+ import org .junit .runner .RunWith ;
3+ import org .junit .runners .Parameterized ;
4+ import org .junit .runners .Parameterized .Parameters ;
5+
6+ import java .util .Arrays ;
7+ import java .util .Collection ;
8+
9+ import static org .junit .Assert .assertEquals ;
10+
11+ @ RunWith (Parameterized .class )
12+ public class BinaryTest {
13+
14+ private String input ;
15+ private int expectedOutput ;
16+
17+ @ Parameters
18+ public static Collection <Object []> data () {
19+ return Arrays .asList (new Object [][]{
20+ {"1" , 1 },
21+ {"10" , 2 },
22+ {"11" , 3 },
23+ {"100" , 4 },
24+ {"1001" , 9 },
25+ {"11010" , 26 },
26+ {"10001101000" , 1128 },
27+ {"2" , 0 },
28+ {"5" , 0 },
29+ {"9" , 0 },
30+ {"134678" , 0 },
31+ {"abc10z" , 0 },
32+ {"011" , 3 }
33+ });
34+ }
35+
36+ public BinaryTest (String input , int expectedOutput ) {
37+ this .input = input ;
38+ this .expectedOutput = expectedOutput ;
39+ }
40+
41+ @ Test
42+ public void test () {
43+ Binary binary = new Binary (input );
44+
45+ assertEquals (expectedOutput , binary .getDecimal ());
46+ }
47+ }
Original file line number Diff line number Diff line change 1818 " gigasecond" ,
1919 " triangle" ,
2020 " scrabble-score" ,
21- " roman-numerals"
21+ " roman-numerals" ,
22+ " binary"
2223 ],
2324 "deprecated" : [
2425 ],
You can’t perform that action at this time.
0 commit comments