-
Notifications
You must be signed in to change notification settings - Fork 0
/
ErrorDetection.java
64 lines (51 loc) · 1.82 KB
/
ErrorDetection.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.Scanner;
public class ErrorDetection {
/* Given a value and a checkbit, return "true" if the check bit matches
* up with the "value", and "false" otherwise. */
private static boolean solveErrorDetection(int value, int checkbit) {
boolean valid = false;
/* ------------------- INSERT CODE HERE ---------------------*/
String binary = get16BitBinary(value);
int num1s = 0;
for (int i = 0; i < binary.length(); i++)
{
if (binary.charAt(i) == '1')
num1s++;
}
valid = (num1s + checkbit) % 2 == 0;
/* -------------------- END OF INSERTION --------------------*/
return valid;
}
/* ------------------- ADDITIONAL CODE INSERTED HERE ---------------------*/
/** Takes an integer, and converts it to a 16 bit integer
*
* @param integer
* @return 16 bit integer as a String
*/
private static String get16BitBinary(int integer)
{
String shortBinary = Integer.toBinaryString(integer);
StringBuilder missingZeroes = new StringBuilder();
for (int i = 0; i < (16 - shortBinary.length()); i++)
{
missingZeroes.append("0");
}
return missingZeroes.toString() + shortBinary;
}
/* -------------------- END OF ADDITIONAL INSERTION --------------------*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numCases = sc.nextInt();
for(int i = 0; i < numCases; i++)
{
int value = sc.nextInt();
int checkbit = sc.nextInt();
if (solveErrorDetection(value, checkbit)) {
System.out.println("Valid");
}
else {
System.out.println("Corrupt");
}
}
}
}