# share my java solution, easy to understand!

• The basic idea is that create a function countx which is used to count and the coefficients of the X and sum of the constant coefficients, and return them!

``````public class Solution {
public String solveEquation(String equation) {
String[] strs=equation.split("=");

int[] left=countX(strs[0]);
int[] right=countX(strs[1]);

if(left[0]==right[0]&&left[1]==right[1]){
return "Infinite solutions";
}else if(left[0]==right[0]&&left[1]!=right[1]){
return "No solution";
}else{
int x=(right[1]-left[1])/(left[0]-right[0]);
return "x="+x;
}
}

public int[] countX(String str){
char[] array=str.toCharArray();
int sign=1;
int countx=0;
int r=0;

int num=1;
for(int i=0;i<array.length;i++){
if(array[i]=='x'){
countx+=sign*num;
}else if(array[i]=='+'){
sign=1;
}else if(array[i]=='-'){
sign=-1;
}else{
num=array[i]-'0';
while(i+1<array.length&&Character.isDigit(array[i+1])){
num=num*10+array[i+1]-'0';
i++;
}
if(i+1<array.length&&array[i+1]!='x'){
r+=sign*num;
num=1;
}else if(i+1==array.length){
r+=sign*num;
num=1;
}
}
}

return new int[]{countx,r};
}
}

``````

• You missed reinitializing num=1 in the if(array[i]=='x') condition.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.