- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.java
More file actions
Latest commit
53 lines (45 loc) · 1.44 KB
/
Copy pathexample.java
File metadata and controls
53 lines (45 loc) · 1.44 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
publicclassBinaryConverter {
publicstaticvoidmain(String[] args){
for(inti = -5; i < 33; i++){
System.out.println(i + ": " + toBinary(i));
System.out.println(i);
//always another way
System.out.println(i + ": " + Integer.toBinaryString(i));
}
}
/*
* pre: none
* post: returns a String with base10Num in base 2
*/
publicstaticStringtoBinary(intbase10Num){
booleanisNeg = base10Num < 0;
base10Num = Math.abs(base10Num);
Stringresult = "";
while(base10Num > 1){
result = (base10Num % 2) + result;
base10Num /= 2;
}
assertbase10Num == 0 || base10Num == 1 : "value is not <= 1: " + base10Num;
result = base10Num + result;
assertall0sAnd1s(result);
if( isNeg )
result = "-" + result;
returnresult;
}
/*
* pre: cal != null
* post: return true if val consists only of characters 1 and 0, false otherwise
*/
publicstaticbooleanall0sAnd1s(Stringval){
assertval != null : "Failed precondition all0sAnd1s. parameter cannot be null";
booleanall = true;
inti = 0;
charc;
while(all && i < val.length()){
c = val.charAt(i);
all = c == '0' || c == '1';
i++;
}
returnall;
}
}