1. 题目
求解一个给定的方程,将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"
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/solve-the-equation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 写的不是很简洁,可优化
- 按
=
号分成两边,把系数加总
class Solution {
public:string solveEquation(string equation) {int i, lnum = 0, rnum = 0, lcoe = 0, rcoe = 0, n=0;char ch;bool positive = true;for(i = 0; equation[i] != '='; ++i){ch = equation[i];if(ch == 'x'){lcoe += n==0 ? ((i>0&&equation[i-1]=='0')? 0 : (positive ? 1 : -1)) : (positive ? n : -n);// 注意考虑 "0x=0" n=0;}else if(ch == '-'){lnum += (positive ? n : -n);positive = false;n=0;}else if(ch == '+'){lnum += (positive ? n : -n);positive = true;n=0;}elsen = 10*n+ch-'0';}if(equation[i-1] != 'x')lnum += (positive ? n : -n);positive = true;n = 0;for(i++; i < equation.size(); ++i){ch = equation[i];if(ch == 'x'){rcoe += n==0 ? ((equation[i-1]=='0')? 0 : (positive ? 1 : -1)) : (positive ? n : -n);n=0;}else if(ch == '-'){rnum += (positive ? n : -n);positive = false;n=0;}else if(ch == '+'){rnum += (positive ? n : -n);positive = true;n=0;}elsen = 10*n+ch-'0';}if(equation[i-1] != 'x')rnum += (positive ? n : -n);if(lcoe == rcoe && lnum == rnum)return "Infinite solutions";if(lcoe == rcoe && lnum != rnum)return "No solution";int ans = (lnum-rnum)/(rcoe-lcoe);return "x="+to_string(ans);}
};
0 ms 6.1 MB
- 优化代码重复段
class Solution {
public:string solveEquation(string equation) {int i, lnum = 0, rnum = 0, lcoe = 0, rcoe = 0, n=0;int pos = equation.find('=');vector<int> coeff = cal_coeff(equation.substr(0,pos));lcoe = coeff[0];lnum = coeff[1];coeff = cal_coeff(equation.substr(pos+1));rcoe = coeff[0];rnum = coeff[1];if(lcoe == rcoe && lnum == rnum)return "Infinite solutions";if(lcoe == rcoe && lnum != rnum)return "No solution";int ans = (lnum-rnum)/(rcoe-lcoe);return "x="+to_string(ans);}vector<int> cal_coeff(string equation){char ch;bool positive = true;int i, n = 0, coe = 0, num = 0;for(i = 0; i < equation.size(); ++i){ch = equation[i];if(ch == 'x'){coe += n==0 ? ((i>0&&equation[i-1]=='0')? 0 : (positive ? 1 : -1)) : (positive ? n : -n);n=0;}else if(ch == '-'){num += (positive ? n : -n);positive = false;n=0;}else if(ch == '+'){num += (positive ? n : -n);positive = true;n=0;}elsen = 10*n+ch-'0';}if(equation[i-1] != 'x')num += (positive ? n : -n);return {coe, num};}
};