Solve a given equation and return the value of x
in the form of string “x=#value”. The equation contains only ‘+’, ‘-‘ operation, the variable x
and its coefficient.
If there is no solution for the equation, return “No solution”.
If there are infinite solutions for the equation, return “Infinite solutions”.
If there is exactly one solution for the equation, we ensure that the value of x
is an integer.
Example 1:
Input: "x+5-3+x=6+x-2" Output: "x=2"
Example 2:
Input: "x=x" Output: "Infinite solutions"
Example 3:
Input: "2x=x" Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2" Output: "x=-1"
Example 5:
Input: "x=x+2" Output: "No solution"
Solution: Parse the equation
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// Author: Huahua, 0 ms, 8.5 MB class Solution { public: string solveEquation(const string& equation) { auto parse = [](string_view s) -> vector<int> { int a{0}, b{0}; int sign = 1; long t = 0; bool d = false; for (char c : s) { if (isdigit(c)) { d = true; t = t * 10 + c - '0'; } else { if (c == 'x') a += (d ? t : 1) * sign; else { b += t * sign; sign = c == '+' ? 1 : -1; } d = false; t = 0; } } b += t * sign; return {a, b}; }; auto pos = equation.find('='); auto l = parse(string_view(equation).substr(0, pos)); auto r = parse(string_view(equation).substr(pos + 1)); l[0] -= r[0]; l[1] -= r[1]; if (l[0] == 0) return l[1] == 0 ? "Infinite solutions" : "No solution"; return "x=" + to_string(-l[1] / l[0]); } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment