|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目描述:
- 求解一个给定的方程,将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
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
- class Solution {
- public:
- #define NO "No solution"
- #define INF "Infinite solutions"
- void helper(string equ, int& num, int& cha){
- int sign = 1;
- int k = 0;
- bool is_x = false;
- for(int i = 0; i < equ.size(); i++){
- char temp = equ[i];
- if(temp == '+' || temp == '-'){
- if(is_x == true){
- cha += sign * k;//注意此处书写
- }else{
- num += sign * k;//注意此处书写
- }
- sign = temp == '-' ? -1 : 1;
- k = 0;
- is_x = false;
- }else if(temp >= '0' && temp <= '9'){
- k = k * 10 + temp - '0';
- }else if(temp == 'x'){
- is_x = true;
- if(k == 0 && (i == 0 || equ[i-1] != '0')){//越界情况不存在
- k = 1;
- }
- }
- }
- }
- string solveEquation(string equation) {
- int store = equation.find('=');
- if(store == -1)return NO;
- int num1 = 0, cha1 = 0;
- int num2 = 0, cha2 = 0;
- helper(equation.substr(0, store) + "+", num1, cha1);
- helper(equation.substr(store+1) + "+", num2, cha2);
- int store1 = num1 - num2;
- int store2 = cha2 - cha1;
- if(store2 == 0){
- return store1 == 0 ? INF : NO;
- }
- return "x=" + to_string(store1 / store2);
- }
- };
复制代码
参考链接:https://leetcode-cn.com/problems ... -shi-huo-qu-chang-/ |
|