生活随笔
收集整理的這篇文章主要介紹了
LeetCode 640. 求解方程(字符串)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
求解一個給定的方程,將x以字符串"x=#value"的形式返回。該方程僅包含’+’,’ - '操作,變量 x 和其對應系數。
如果方程沒有解,請返回“No solution”。
如果方程有無限解,則返回“Infinite solutions”。
如果方程中只有一個解,保證返回值 x 是一個整數。
示例
1:
輸入
: "x+5-3+x=6+x-2"
輸出
: "x=2"示例
2:
輸入
: "x=x"
輸出
: "Infinite solutions"示例
3:
輸入
: "2x=x"
輸出
: "x=0"示例
4:
輸入
: "2x+3x-6x=x+2"
輸出
: "x=-1"示例
5:
輸入
: "x=x+2"
輸出
: "No solution"
來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/solve-the-equation
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
class Solution {
public:string
solveEquation(string equation
) {int i
, lnum
= 0, rnum
= 0, lcoe
= 0, rcoe
= 0, n
=0;char ch
;bool positive
= true;for(i
= 0; equation
[i
] != '='; ++i
){ch
= equation
[i
];if(ch
== 'x'){lcoe
+= n
==0 ? ((i
>0&&equation
[i
-1]=='0')? 0 : (positive
? 1 : -1)) : (positive
? n
: -n
);n
=0;}else if(ch
== '-'){lnum
+= (positive
? n
: -n
);positive
= false;n
=0;}else if(ch
== '+'){lnum
+= (positive
? n
: -n
);positive
= true;n
=0;}elsen
= 10*n
+ch
-'0';}if(equation
[i
-1] != 'x')lnum
+= (positive
? n
: -n
);positive
= true;n
= 0;for(i
++; i
< equation
.size(); ++i
){ch
= equation
[i
];if(ch
== 'x'){rcoe
+= n
==0 ? ((equation
[i
-1]=='0')? 0 : (positive
? 1 : -1)) : (positive
? n
: -n
);n
=0;}else if(ch
== '-'){rnum
+= (positive
? n
: -n
);positive
= false;n
=0;}else if(ch
== '+'){rnum
+= (positive
? n
: -n
);positive
= true;n
=0;}elsen
= 10*n
+ch
-'0';}if(equation
[i
-1] != 'x')rnum
+= (positive
? n
: -n
);if(lcoe
== rcoe
&& lnum
== rnum
)return "Infinite solutions";if(lcoe
== rcoe
&& lnum
!= rnum
)return "No solution";int ans
= (lnum
-rnum
)/(rcoe
-lcoe
);return "x="+to_string(ans
);}
};
0 ms 6.1 MB
class Solution {
public:string
solveEquation(string equation
) {int i
, lnum
= 0, rnum
= 0, lcoe
= 0, rcoe
= 0, n
=0;int pos
= equation
.find('=');vector
<int> coeff
= cal_coeff(equation
.substr(0,pos
));lcoe
= coeff
[0];lnum
= coeff
[1];coeff
= cal_coeff(equation
.substr(pos
+1));rcoe
= coeff
[0];rnum
= coeff
[1];if(lcoe
== rcoe
&& lnum
== rnum
)return "Infinite solutions";if(lcoe
== rcoe
&& lnum
!= rnum
)return "No solution";int ans
= (lnum
-rnum
)/(rcoe
-lcoe
);return "x="+to_string(ans
);}vector
<int> cal_coeff(string equation
){char ch
;bool positive
= true;int i
, n
= 0, coe
= 0, num
= 0;for(i
= 0; i
< equation
.size(); ++i
){ch
= equation
[i
];if(ch
== 'x'){coe
+= n
==0 ? ((i
>0&&equation
[i
-1]=='0')? 0 : (positive
? 1 : -1)) : (positive
? n
: -n
);n
=0;}else if(ch
== '-'){num
+= (positive
? n
: -n
);positive
= false;n
=0;}else if(ch
== '+'){num
+= (positive
? n
: -n
);positive
= true;n
=0;}elsen
= 10*n
+ch
-'0';}if(equation
[i
-1] != 'x')num
+= (positive
? n
: -n
);return {coe
, num
};}
};
總結
以上是生活随笔為你收集整理的LeetCode 640. 求解方程(字符串)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。