Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit ec0b396

Browse files
refactor 640
1 parent 3a2d3bc commit ec0b396

File tree

1 file changed

+28
-26
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+28
-26
lines changed

src/main/java/com/fishercoder/solutions/_640.java

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -34,35 +34,37 @@
3434
3535
*/
3636
public class _640 {
37-
/**
38-
* Reference: https://discuss.leetcode.com/topic/95203/concise-java-solution/7
39-
*/
40-
public String solveEquation(String equation) {
41-
String[] parts = equation.split("=");
42-
int[] left = evaluate(parts[0]);
43-
int[] right = evaluate(parts[1]);
44-
if (left[0] == right[0] && left[1] == right[1]) {
45-
return "Infinite solutions";
46-
} else if (left[0] == right[0]) {
47-
return "No solution";
37+
public static class Solution1 {
38+
/**
39+
* Reference: https://discuss.leetcode.com/topic/95203/concise-java-solution/7
40+
*/
41+
public String solveEquation(String equation) {
42+
String[] parts = equation.split("=");
43+
int[] left = evaluate(parts[0]);
44+
int[] right = evaluate(parts[1]);
45+
if (left[0] == right[0] && left[1] == right[1]) {
46+
return "Infinite solutions";
47+
} else if (left[0] == right[0]) {
48+
return "No solution";
49+
}
50+
return "x=" + (right[1] - left[1]) / (left[0] - right[0]);
4851
}
49-
return "x=" + (right[1] - left[1]) / (left[0] - right[0]);
50-
}
5152

52-
private int[] evaluate(String part) {
53-
int[] result = new int[2];//result[0] is the coefficient for x, result[1] is the coefficient for constants
54-
String[] tokens = part.split("(?=[+-])"); // ()for match group; ?= for match and include in res; [+-] means + or -;
55-
for (String token : tokens) {
56-
if (token.equals("+x") || token.equals("x")) {
57-
result[0]++;
58-
} else if (token.equals("-x")) {
59-
result[0]--;
60-
} else if (token.contains("x")) {
61-
result[0] += Integer.parseInt(token.substring(0, token.length() - 1));
62-
} else {
63-
result[1] += Integer.parseInt(token);
53+
private int[] evaluate(String part) {
54+
int[] result = new int[2];//result[0] is the coefficient for x, result[1] is the coefficient for constants
55+
String[] tokens = part.split("(?=[+-])"); // ()for match group; ?= for match and include in res; [+-] means + or -;
56+
for (String token : tokens) {
57+
if (token.equals("+x") || token.equals("x")) {
58+
result[0]++;
59+
} else if (token.equals("-x")) {
60+
result[0]--;
61+
} else if (token.contains("x")) {
62+
result[0] += Integer.parseInt(token.substring(0, token.length() - 1));
63+
} else {
64+
result[1] += Integer.parseInt(token);
65+
}
6466
}
67+
return result;
6568
}
66-
return result;
6769
}
6870
}

0 commit comments

Comments
 (0)