鱼C论坛

 找回密码
 立即注册
查看: 2247|回复: 0

[技术交流] C++刷leetcode(640. 求解方程)【数学】

[复制链接]
发表于 2020-7-27 12:53:23 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

  2. 如果方程没有解,请返回“No solution”。

  3. 如果方程有无限解,则返回“Infinite solutions”。

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

  5. 示例 1:

  6. 输入: "x+5-3+x=6+x-2"
  7. 输出: "x=2"
  8. 示例 2:

  9. 输入: "x=x"
  10. 输出: "Infinite solutions"
  11. 示例 3:

  12. 输入: "2x=x"
  13. 输出: "x=0"
  14. 示例 4:

  15. 输入: "2x+3x-6x=x+2"
  16. 输出: "x=-1"
  17. 示例 5:

  18. 输入: "x=x+2"
  19. 输出: "No solution"

  20. 来源:力扣(LeetCode)
  21. 链接:https://leetcode-cn.com/problems/solve-the-equation
  22. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码

  1. class Solution {
  2. public:
  3.     #define NO "No solution"
  4.     #define INF "Infinite solutions"
  5.     void helper(string equ, int& num, int& cha){
  6.         int sign = 1;
  7.         int k = 0;
  8.         bool is_x = false;
  9.         for(int i = 0; i < equ.size(); i++){
  10.             char temp = equ[i];
  11.             if(temp == '+' || temp == '-'){
  12.                 if(is_x == true){
  13.                     cha += sign * k;//注意此处书写
  14.                 }else{
  15.                     num += sign * k;//注意此处书写
  16.                 }
  17.                 sign = temp == '-' ? -1 : 1;
  18.                 k = 0;
  19.                 is_x = false;
  20.             }else if(temp >= '0'  && temp <= '9'){
  21.                 k = k * 10 + temp - '0';
  22.             }else if(temp == 'x'){
  23.                 is_x = true;
  24.                 if(k == 0 && (i == 0 || equ[i-1] != '0')){//越界情况不存在
  25.                     k = 1;
  26.                 }
  27.             }
  28.         }
  29.     }
  30.     string solveEquation(string equation) {
  31.         int store = equation.find('=');
  32.         if(store == -1)return NO;
  33.         int num1 = 0, cha1 = 0;
  34.         int num2 = 0, cha2 = 0;
  35.         helper(equation.substr(0, store) + "+", num1, cha1);
  36.         helper(equation.substr(store+1) + "+", num2, cha2);
  37.         int store1 = num1 - num2;
  38.         int store2 = cha2 - cha1;
  39.         if(store2 == 0){
  40.             return store1 == 0 ? INF : NO;
  41.         }
  42.         return "x=" + to_string(store1 / store2);
  43.     }
  44. };
复制代码


参考链接:https://leetcode-cn.com/problems ... -shi-huo-qu-chang-/

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-20 02:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表