当前位置:网站首页>LeetCode·每日一题·640.求解方程·模拟构造
LeetCode·每日一题·640.求解方程·模拟构造
2022-08-10 12:12:00 【小迅想变强】
链接:https://leetcode.cn/problems/solve-the-equation/solution/mo-ni-by-xun-ge-v-5m9w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目
示例
思路
解题思路
根据题意直接模拟计算过程即可
具体实现
为了方便定义两个变量,一个factor保存x的系数,一个val保存常量的值,然后遍历枚举字符串所有元素,将对应元素转换,最后判断factor和val的值
代码
#define MAX_EXPRESSION_LEN 32
char * solveEquation(char * equation) {
int factor = 0, val = 0;
int index = 0, n = strlen(equation), sign1 = 1; // 等式左边默认系数为正
while (index < n) {
//判断是等号左边还是右边
if (equation[index] == '=') {
sign1 = -1; // 等式右边默认系数为负
index++;
continue;
}
int sign2 = sign1, number = 0;
bool valid = false; // 记录 number 是否有效,为了后面判断x的系数方便
if (equation[index] == '-' || equation[index] == '+') { // 去掉前面的符号
sign2 = (equation[index] == '-') ? -sign1 : sign1;
index++;
}
//将数值转换一下,但是还不能确定是不是x的系数还是常量
while (index < n && isdigit(equation[index])) {
number = number * 10 + (equation[index] - '0');
index++;
valid = true;
}
//判断是变量还是数值
if (index < n && equation[index] == 'x') { // 变量
factor += valid ? sign2 * number : sign2;
index++;
} else { // 数值
val += sign2 * number;
}
}
if (factor == 0) {
return val == 0 ? "Infinite solutions" : "No solution";
}
char *ans = (char *)malloc(sizeof(char) * MAX_EXPRESSION_LEN);
sprintf(ans, "x=%d", - val / factor);
return ans;
}
作者:xun-ge-v
链接:https://leetcode.cn/problems/solve-the-equation/solution/mo-ni-by-xun-ge-v-5m9w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。边栏推荐
- What are the five common data types of Redis?What is the corresponding data storage space?Take you to learn from scratch
- AICOCO AI Frontier Promotion (8.10)
- 查看 CUDA cudnn 版本 & 测试 cuda 和 cudnn 有效性「建议收藏」
- 中科院深圳先进技术院合成所赵国屏院士组2022年招聘启事
- Deploy the project halfway through the follow-up
- Twikoo腾讯云函数部署转移到私有部署
- odps sql 不支持 unsupported feature CREATE TEMPORARY
- 娄底污水处理厂实验室建设管理
- LT8911EXB MIPI CSI/DSI to EDP signal conversion
- 实践为主,理论为辅!腾讯大佬MySQL高阶宝典震撼来袭!
猜你喜欢
随机推荐
中科院深圳先进技术院合成所赵国屏院士组2022年招聘启事
金山云要飘到哪里?
「网络架构」网络代理第一部分: 代理概述
Is there a problem with the CURRENT_TIMESTAMP(6) function?
sprintboot项目通过interceptor和filter实现接入授权控制
AtCoder初学者比赛077 D -小多
实践为主,理论为辅!腾讯大佬MySQL高阶宝典震撼来袭!
Common examples of regular expressions
如何培养ui设计师的设计思维?
Prada, big show?In the yuan in the universe that!
Polygon zkEVM工具——PIL和CIRCOM
[Advanced Digital IC Verification] Difference and focus analysis between SoC system verification and IP module verification
Behind IDC's No. 1 position, what kind of "video cloud" is Alibaba Cloud building?
线代 | 秒杀方法与技巧
专有云ABC Stack,真正的实力派!
Chapter9 : De Novo Molecular Design with Chemical Language Models
MySQL相关问题整理
es6-promise对象详解
Data Analysis of Time Series (5): Simple Prediction Method
Chapter9 : De Novo Molecular Design with Chemical Language Models









