当前位置:网站首页>365天挑战LeetCode1000题——Day 053 求解方程 解析 模拟
365天挑战LeetCode1000题——Day 053 求解方程 解析 模拟
2022-08-10 18:29:00 【ShowM3TheCode】
640. 求解方程
代码实现(自解)
class Solution {
private:
void parse(string str, int& x, int& co) {
int pstr = 0;
int n = str.size();
bool flag = false;
string tmp = "";
int val = 0;
x = 0, co = 0;
while (pstr != n) {
if (str[pstr] == '-') {
flag = true;
pstr++;
}
else if (str[pstr] == '+') {
pstr++;
}
while (str[pstr] >= '0' && str[pstr] <= '9') {
tmp += str[pstr++];
}
if (str[pstr] == 'x') {
if (tmp == "") val = 1;
else val = stoi(tmp);
if (flag) x -= val;
else x += val;
}
else {
if (flag) co -= stoi(tmp);
else co += stoi(tmp);
pstr--;
}
pstr++;
flag = false;
tmp = "";
}
}
public:
string solveEquation(string equation) {
int equal = equation.find('=', 0);
string left = equation.substr(0, equal);
string right = equation.substr(equal + 1);
int x1, co1, x2, co2;
parse(left, x1, co1);
parse(right, x2, co2);
// cout << "x1 : " << x1 << ", co1 : " << co1 << endl;
// cout << "x2 : " << x2 << ", co2 : " << co2 << endl;
if (x1 == x2 && co1 == co2) return "Infinite solutions";
if (x1 == x2 && co1 != co2) return "No solution";
return "x=" + to_string((co2 - co1) / (x1 - x2));
}
};
边栏推荐
猜你喜欢
随机推荐
搭载2.8K 120Hz OLED华硕好屏 无畏Pro15 2022锐龙版屏开得胜
Unity_Stack<T>()的应用(多个次级界面后的返回逻辑)
EasyGBS连接mysql数据库提示“can’t connect to mysql server”,如何解决?
const的自己理解
【HMS core】【FAQ】Account Kit、push Kit典型问题合集1
弘玑Cyclone与风变科技达成战略合作:优势互补聚焦数字化人才培养
兼具外观、性能、屏幕!华硕灵耀X 14火热抢购中
[Image segmentation] Image segmentation based on cellular automata with matlab code
Three schemes of SQL query across the table
FlexSim仿真软件入门笔记:基本操作、快捷键
[TAPL] 概念笔记
shell运算详解,看这一篇就够了!
2022-08-09 Study Notes day32-IO Stream
智能安防产品公司及产品
类型和id对应的两个数组
【HMS core】【FAQ】Analytics Kit、Push Kit典型问题合集3
flex使用align-content无效
第14章_MySQL事务日志
set和map使用讲解
三坐标雷达显示软件 SPx Viewer-3D