Skip to content

Instantly share code, notes, and snippets.

@lucoram
Created November 12, 2020 20:38
Show Gist options
  • Save lucoram/ef4c73a469730ef82e9250437acf713b to your computer and use it in GitHub Desktop.
Save lucoram/ef4c73a469730ef82e9250437acf713b to your computer and use it in GitHub Desktop.
int C2(String s) {
s = s.replace(" ", "");
String t = s.replaceAll("[0-9x^&|~()]", "");
if(!t.isEmpty()) {
return -1;
}
for (int i = 1; i <= 1000; i++) {
String c = s.replace("x", String.valueOf(i));
if (eval(c) == 0) {
return i;
}
}
return -1;
}
int eval(String s) {
String exp = "";
String sub = "";
int level = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
level++;
if (level > 1) {
sub += c;
}
continue;
}
if (c == ')') {
level--;
if (level == 0) {
exp += eval(sub);
sub = "";
} else {
sub += c;
}
continue;
}
if (level > 0 || !sub.isEmpty()) {
sub += c;
} else {
exp += c;
}
}
return calc(exp);
}
int calc(String exp) {
String left = "";
String right = "";
String op = "";
for (char d : exp.toCharArray()) {
if (Character.isDigit(d)) {
if (op.isEmpty()) {
left += d;
} else {
right += d;
}
} else {
if (op.isEmpty()) {
op = String.valueOf(d);
continue;
} else {
left = "" + doMath(left, right, op);
op = "";
right = "";
}
}
}
if (!op.isEmpty()) {
left = "" + doMath(left, right, op);
}
return Integer.parseInt(left);
}
int doMath(String left, String right, String op) {
if (!left.isEmpty() && !right.isEmpty()) {
// ^,&,|,~
switch (op) {
case "^":
return Integer.parseInt(left) ^ Integer.parseInt(right);
case "&":
return Integer.parseInt(left) & Integer.parseInt(right);
case "|":
return Integer.parseInt(left) | Integer.parseInt(right);
}
}
else if (left.isEmpty() && !right.isEmpty() && op.equals("~")) {
return ~Integer.parseInt(right);
}
throw new RuntimeException();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment