|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 640. Solve the Equation |
| 5 | + * |
| 6 | + * Solve a given equation and return the value of x in the form of string "x=#value". |
| 7 | + * The equation contains only '+', '-' operation, the variable x and its coefficient. |
| 8 | +
|
| 9 | + If there is no solution for the equation, return "No solution". |
| 10 | +
|
| 11 | + If there are infinite solutions for the equation, return "Infinite solutions". |
| 12 | +
|
| 13 | + If there is exactly one solution for the equation, we ensure that the value of x is an integer. |
| 14 | +
|
| 15 | + Example 1: |
| 16 | + Input: "x+5-3+x=6+x-2" |
| 17 | + Output: "x=2" |
| 18 | +
|
| 19 | + Example 2: |
| 20 | + Input: "x=x" |
| 21 | + Output: "Infinite solutions" |
| 22 | +
|
| 23 | + Example 3: |
| 24 | + Input: "2x=x" |
| 25 | + Output: "x=0" |
| 26 | +
|
| 27 | + Example 4: |
| 28 | + Input: "2x+3x-6x=x+2" |
| 29 | + Output: "x=-1" |
| 30 | +
|
| 31 | + Example 5: |
| 32 | + Input: "x=x+2" |
| 33 | + Output: "No solution" |
| 34 | +
|
| 35 | + */ |
| 36 | +public class _640 { |
| 37 | + /**Reference: https://discuss.leetcode.com/topic/95203/concise-java-solution/7*/ |
| 38 | + public String solveEquation(String equation) { |
| 39 | + String[] parts = equation.split("="); |
| 40 | + int[] left = evaluate(parts[0]); |
| 41 | + int[] right = evaluate(parts[1]); |
| 42 | + if (left[0] == right[0] && left[1] == right[1]) return "Infinite solutions"; |
| 43 | + else if (left[0] == right[0]) return "No solution"; |
| 44 | + return "x=" + (right[1] - left[1]) / (left[0] - right[0]); |
| 45 | + } |
| 46 | + |
| 47 | + private int[] evaluate(String part) { |
| 48 | + int[] result = new int[2];//result[0] is the coefficient for x, result[1] is the coefficient for constants |
| 49 | + String[] tokens = part.split("(?=[+-])"); // ()for match group; ?= for match and include in res; [+-] means + or -; |
| 50 | + for (String token : tokens) { |
| 51 | + if (token.equals("+x") || token.equals("x")) result[0]++; |
| 52 | + else if (token.equals("-x")) result[0]--; |
| 53 | + else if (token.contains("x")) { |
| 54 | + result[0] += Integer.parseInt(token.substring(0, token.length()-1)); |
| 55 | + } else { |
| 56 | + result[1] += Integer.parseInt(token); |
| 57 | + } |
| 58 | + } |
| 59 | + return result; |
| 60 | + } |
| 61 | +} |
0 commit comments