码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 640.求解方程

时间:2019-02-15 13:39:56      阅读:365      评论:0      收藏:0      [点我收藏+]

标签:infinite   else   class   src   ring   info   for   整数   white   

求解方程

求解一个给定的方程,将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 }

 

Leetcode 640.求解方程

标签:infinite   else   class   src   ring   info   for   整数   white   

原文地址:https://www.cnblogs.com/kexinxin/p/10383055.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!