Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created September 1, 2017 17:33
Show Gist options
  • Save cixuuz/3be8bfa7bfc6121d5b738de951033f16 to your computer and use it in GitHub Desktop.
Save cixuuz/3be8bfa7bfc6121d5b738de951033f16 to your computer and use it in GitHub Desktop.
[640. Solve the Equation] #leetcode
class Solution {
// O(n) O(1)
public String solveEquation(String equation) {
int x = 0, c = 0, num = -1, sign = 1;
boolean flag = false; // if at right of equal sign
for (int i = 0; i < equation.length(); i++) {
Character s = equation.charAt(i);
if (Character.isDigit(s)) {
if (num == -1) {
num = Character.getNumericValue(s);
} else {
num = 10*num + Character.getNumericValue(s);
}
}
if (s.equals('x')) {
if (flag) {
x -= sign*(num == -1? 1 : num);
} else {
x += sign*(num == -1? 1 : num);
}
num = -1;
}
if (s.equals('+')) {
if (num != -1) {
if (flag) {
c += sign*num;
} else {
c -= sign*num;
}
num = -1;
}
sign = 1;
}
if (s.equals('-')) {
if (num != -1) {
if (flag) {
c += sign*num;
} else {
c -= sign*num;
}
num = -1;
}
sign = -1;
}
if (s.equals('=')) {
if (num != -1) {
if (flag) {
c += sign*num;
} else {
c -= sign*num;
}
num = -1;
}
flag = true;
sign = 1;
}
}
if (num != -1) {
if (flag) {
c += sign*num;
} else {
c -= sign*num;
}
num = -1;
}
System.out.printf("%d %d %d", x, c, num);
if (x == 0 && c == 0) return "Infinite solutions";
if (x == 0) return "No solution";
return String.format("x=%1$d", c/x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment