leetcode 640. Solve the Equation 等式计算 + C++stringstream的一个很好地示范

ゝ一世哀愁。 2022-06-03 06:42 241阅读 0赞

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”

本题题意很简单,就是直接分析即可,注意使用C++的stringstream来处理,就是有点烦,别的都很简单

建议和leetcode 609. Find Duplicate File in System C++stringstream的一个很好地示范 一起学习

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <set>
  6. #include <unordered_set>
  7. #include <queue>
  8. #include <stack>
  9. #include <string>
  10. #include <climits>
  11. #include <algorithm>
  12. #include <sstream>
  13. #include <functional>
  14. #include <bitset>
  15. #include <numeric>
  16. #include <cmath>
  17. #include <regex>
  18. #include <iomanip>
  19. using namespace std;
  20. class Solution
  21. {
  22. public:
  23. string solveEquation(string equation)
  24. {
  25. int index = equation.find('=');
  26. vector<int> left = getRes(equation.substr(0, index));
  27. vector<int> right = getRes(equation.substr(index + 1));
  28. int x = left[0] - right[0];
  29. int num = right[1] - left[1];
  30. string res = "";
  31. if (x == 0 && num == 0)
  32. res = "Infinite solutions";
  33. else if (x == 0 && num != 0)
  34. res = "No solution";
  35. else
  36. res = "x=" + to_string(num / x);
  37. return res;
  38. }
  39. vector<int> getRes(string eq)
  40. {
  41. vector<int> res;
  42. stringstream ss(eq);
  43. char c;
  44. int num = 0, x = 0, tmp;
  45. string a = "";
  46. for (int i = 0; i <= eq.length(); i++)
  47. {
  48. if (i<eq.length())
  49. ss >> c;
  50. if (c == '+' || c == '-' || i == eq.length())
  51. {
  52. if (a.size() >= 1)
  53. {
  54. if (a.back() == 'x')
  55. {
  56. if (a == "x" || a == "+x")
  57. tmp = 1;
  58. else if (a == "-x")
  59. tmp = -1;
  60. else
  61. tmp = stoi(a.substr(0, a.length() - 1));
  62. x += tmp;
  63. }
  64. else
  65. {
  66. tmp = stoi(a);
  67. num += tmp;
  68. }
  69. }
  70. if (c == '-')
  71. a = "-";
  72. else
  73. a = "";
  74. }
  75. else
  76. a += c;
  77. }
  78. res = { x,num };
  79. return res;
  80. }
  81. };

发表评论

表情:
评论列表 (有 0 条评论,241人围观)

还没有评论,来说两句吧...

相关阅读