LeetCode 640 题解

https://leetcode.com/problems/solve-the-equation/description/

题目大意:给你一个有x,+,-组成的算式,计算x的值。

解题思路:split分割成两边,分别统计x和数字的多少,最后比较。

用Java写的时候遇到了一点问题,我想用一个函数实现统计x和数字的多少,但是Java里函数传入的参数 是int的时候没有指针的概念,得包装成一个对象。

class Solution {
    private void fun(Myvalue x,String s)
    {
        int xNum = x.x;
        int val = x.v;
        s+="+";
        int len =s.length();
        
        int pre =-1; // -1 表示前面是空; 1表示前面是x ; 2表示前面是符号; 3表示前面是数字
        int f = 1; // 1表示+ -1表示-
        int num =0;

        for(int i=0;i<len;i++)
        {
            char tmp = s.charAt(i);
            if(tmp>='0' && tmp<='9')
            {
                num = num*10+(tmp-'0') ;
                pre= 3;
            }
            else if(tmp=='x')
            {
                if(pre == 3)
                {
                    if(f==-1)
                        xNum -= num;
                    else
                        xNum += num;
                    num=0;
                    pre=1;
                }
                else
                {
                    if(f==-1)
                        xNum-=1;
                    else
                        xNum+=1;
                    pre=1;
                }
            }
            else
            {
                if(pre==1)
                    ;
                else if(pre==3)
                {
                    if(f==1)
                        val+=num;
                    else
                        val-=num;
                    num=0;
                }
                pre=2;
                if(tmp=='+') f=1;
                else f=-1;
            }
        }
        x.x = xNum;
        x.v = val;
//        System.out.println(xNum+" "+val);
    }
    public String solveEquation(String equation) {
        String[] s=equation.split("=");
//        Integer leftxNum=new Integer(0),rightxNum=new Integer(0),left=new Integer(0),right=new Integer(0);
        Myvalue left = new Myvalue(0,0),right=new Myvalue(0,0);

        fun(left,s[0]);
        fun(right,s[1]);

//        System.out.println(left.x+" "+right.x);
        int x = left.x - right.x ;
        int v = right.v-left.v;
        if(x==0 && v==0)
            return "Infinite solutions";
        else
        {
            if(x!=0)
            {
                if( v/x * x ==v)
                    return "x="+String.valueOf(v/x) ;
            }
            return "No solution";
        }
    }
}


class Myvalue{
    int x;
    int v;

    public Myvalue(int x, int v) {
        this.x = x;
        this.v = v;
    }
}

猜你喜欢

转载自blog.csdn.net/u011439455/article/details/80453152