当前位置:网站首页>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));
}
};
边栏推荐
猜你喜欢
随机推荐
Consul Introduction and Installation
微服务架构-实现技术之六大基础组件:服务通信+事件驱动+负载均衡+服务路由+API网关+配置管理
从企业的视角来看,数据中台到底意味着什么?
【HMS core】【FAQ】Account Kit、push Kit典型问题合集1
MySQL安装步骤
云渲染的应用正在扩大,越来越多的行业需要可视化服务
关于奉加微PHY62xx系列如何选型?PHY6222/PHY6212/PHY6252
报告详解影响英特尔10/11/12代酷睿处理器的ÆPIC Leak安全漏洞
消息队列初见:一起聊聊引入系统mq 之后的问题
关于技术分享的思考
Redis command---key chapter (super complete)
第15章_锁
AIRIOT答疑第8期|AIRIOT的金字塔服务体系是如何搞定客户的?
API 网关的功能
003-序列图(一)
人生苦短,开始用go
想玩转监控神器Prometheus吗?
补坑求逆序对
哈夫曼实现文件压缩解压缩(c语言)
罗克韦尔Rockwell Automation EDI 项目