# JAVA程序设计：求解方程（LeetCode：640）

class Solution {
public String solveEquation(String equation) {

int sum=0;
boolean right=false;
boolean isFushu=false;
int[] a=new int[2];

for(int i=0;i<equation.length();i++) {
if(equation.charAt(i)>='0' && equation.charAt(i)<='9') {
sum=sum*10+equation.charAt(i)-'0';
if(i==equation.length()-1) {
work(0,a,sum,isFushu,right);
continue;
}
}
else {
if(equation.charAt(i)=='x') {
if(i==0 || i>0 && (equation.charAt(i-1)<'0' || equation.charAt(i-1)>'9'))
sum=1;
work(1,a,sum,isFushu,right);
isFushu=false;
}
else {
if(i>0 && equation.charAt(i-1)!='x')
work(0,a,sum,isFushu,right);
isFushu=false;
if(equation.charAt(i)=='-') isFushu=true;
else if(equation.charAt(i)=='=') right=true;
}
sum=0;
}
}

if(a[1]==0 && a[0]!=0) return "No solution";
if(a[1]==0 && a[0]==0) return "Infinite solutions";
if(a[0]==0) return "x=0";
return "x="+String.valueOf(-a[0]/a[1]);
}

private void work(int id,int[] a,int sum,boolean isFushu,boolean right) {
a[id]+=((isFushu==true && right==false ||  isFushu==false && right==true)?-sum:sum);
}
}

©️2019 CSDN 皮肤主题: 程序猿惹谁了 设计师: 上身试试