[leetcode] 640. Solve the Equation

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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"

分析

题目的意思是:给定一个字符串等式,求解x。

  • 等式左边sign=1,等式右边sign=-1;b用来累加数,a用来累加符号x上的数。然后-b/a就是结果了哈,注意无解和无穷解的情况。无解a=0&&b!=0,无穷解a=0&&b=0。

代码

class Solution {
public:
    string solveEquation(string equation) {
        int n=equation.size();
        int j=0;
        int sign=1;
        int b=0,a=0;
        for(int i=0;i<n;i++){
            if(equation[i]=='+'||equation[i]=='-'){
                if(i>j){
                    b+=stoi(equation.substr(j,i-j))*sign;
                }
                j=i;
            }else if(equation[i]=='x'){
                if(i==j||equation[i-1]=='+'){
                    a+=sign;
                }else if(equation[i-1]=='-'){
                    a-=sign;
                }else{
                    a+=stoi(equation.substr(j,i-j))*sign;
                }
                j=i+1;
            }else if(equation[i]=='='){
                if(i>j){
                    b+=stoi(equation.substr(j,i-j))*sign;
                }
                sign=-1;
                j=i+1;
            }
        }
        if(j<n) b+=stoi(equation.substr(j))*sign;
        if(a==0&&b==a) return "Infinite solutions";
        if(a==0&&a!=b) return "No solution";
        return "x="+to_string(-b/a);
    }
};

参考文献

[LeetCode] Solve the Equation 解方程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值