当前位置:网站首页>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));
}
};
边栏推荐
猜你喜欢
随机推荐
MySQL数据高级查询之连接查询、联合查询、子查询[通俗易懂]
stm32中的CAN通讯列表模式配置解析与源码
CSV(Comma-Separate-Values)逗号分隔值文件
罗克韦尔Rockwell Automation EDI 项目
关于技术分享的思考
剑指 Offer II 042. 最近请求次数-队列法
【FAQ】【Push Kit】 华为怎么设置角标
三星Galaxy Watch5产品图片流出 非Pro表款亦有蓝宝石加持
三坐标雷达显示软件 SPx Viewer-3D
How to choose Fengjiawei PHY62xx series?PHY6222/PHY6212/PHY6252
什么是企业知识库?有什么作用?如何搭建?
Consul Introduction and Installation
接口测试进阶接口脚本使用—apipost(预/后执行脚本)
入门:人脸专集2 | 人脸关键点检测汇总(文末有相关文章链接)
漫谈测试成长之探索——测试文档
Interface test advanced interface script using -apipost (pre/post execution script)
记录某博彩网站渗透
微信小程序富文本标签rich-text
flex使用align-content无效
【接入指南 之 直接接入】手把手教你快速上手接入HONOR Connect平台(下)