等号左右两边代码一样,就是+ - 不一样
将x都移到左边 整数移到右边
class Solution { public: int change(string str) { if(str == "0") return 1; int len = str.length(); int ret = 0; for(int i = 0; i < len; i++) { ret = ret * 10 + str[i] - '0'; } return ret; } string rev(int x) { if(x == 0) return "0"; string str = ""; while(x) { int tmp = x % 10; x /= 10; str += '0' + tmp; } reverse(str.begin(), str.end()); return str; } string solveEquation(string equation) { int cnt1 = 0, cnt2 = 0, f = 0, s; int len = equation.length(); string str; int i = 0; while(i < len) { s = 0; str = "0"; if(equation[i] == '=') { f = 1; i++; } if(equation[i] == '-') { s = 1; i++; } else if(equation[i] == '+') i++; if(f == 1) { while(equation[i] >= '0' && equation[i] <= '9') str += equation[i++]; if(equation[i] == 'x') { if(s == 0) cnt2 -= change(str); else cnt2 += change(str); i++; } else { if(s == 0) cnt1 += change(str); else cnt1 -= change(str); } } else { while(equation[i] >= '0' && equation[i] <= '9') str += equation[i++]; if(equation[i] == 'x') { if(s == 0) cnt2 += change(str); else cnt2 -= change(str); i++; } else { // cout << str << endl; if(s == 0) cnt1 -= change(str); else cnt1 += change(str); } } } // cout << cnt2 << " " << cnt1 << endl; if(cnt2 == 0) if(cnt1 == 0) str = "Infinite solutions"; else str = "No solution"; else { str = "x="; int tmp = cnt1 / cnt2; if(tmp < 0) str += '-', tmp = -tmp; // cout << tmp << endl; str += rev(tmp); } return str; } };