Leetcode 640.求解方程

求解方程

求解一个给定的方程,将x以字符串"x=#value"的形式返回。该方程仅包含'+',' - '操作,变量 x 和其对应系数。

如果方程没有解,请返回"No solution"。

如果方程有无限解,则返回"Infinite solutions"。

如果方程中只有一个解,要保证返回值 x 是一个整数。

示例 1:

输入: "x+5-3+x=6+x-2"

输出: "x=2"

示例 2:

输入: "x=x"

输出: "Infinite solutions"

示例 3:

输入: "2x=x"

输出: "x=0"

示例 4:

输入: "2x+3x-6x=x+2"

输出: "x=-1"

示例 5:

输入: "x=x+2"

输出: "No solution"

 

 

 1 public class Solution {
 2     public String coeff(String x) {
 3         if (x.length() > 1 && x.charAt(x.length() - 2) >= '0' && x.charAt(x.length() - 2) <= '9')
 4             return x.replace("x", "");
 5         return x.replace("x", "1");
 6     }
 7     public String solveEquation(String equation) {
 8         String[] lr = equation.split("=");
 9         int lhs = 0, rhs = 0;
10         for (String x: breakIt(lr[0])) {
11             if (x.indexOf("x") >= 0) {
12                 lhs += Integer.parseInt(coeff(x));
13             } else
14                 rhs -= Integer.parseInt(x);
15         }
16         for (String x: breakIt(lr[1])) {
17             if (x.indexOf("x") >= 0)
18                 lhs -= Integer.parseInt(coeff(x));
19             else
20                 rhs += Integer.parseInt(x);
21         }
22         if (lhs == 0) {
23             if (rhs == 0)
24                 return "Infinite solutions";
25             else
26                 return "No solution";
27         }
28         return "x=" + rhs / lhs;
29     }
30     public List < String > breakIt(String s) {
31         List < String > res = new ArrayList < > ();
32         String r = "";
33         for (int i = 0; i < s.length(); i++) {
34             if (s.charAt(i) == '+' || s.charAt(i) == '-') {
35                 if (r.length() > 0)
36                     res.add(r);
37                 r = "" + s.charAt(i);
38             } else
39                 r += s.charAt(i);
40         }
41         res.add(r);
42         return res;
43     }
44 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10383055.html
今日推荐