当前位置:网站首页>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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
- 48 the mysql database
- 实践为主,理论为辅!腾讯大佬MySQL高阶宝典震撼来袭!
- 郭晶晶家的象棋私教,好家伙是个机器人
- 你是怎么知道数据库 Htap 能力强弱的?怎么能看出来
- 48MySQL数据库基础
- The god-level Alibaba "high concurrency" tutorial - basic + actual combat + source code + interview + architecture is all-inclusive
- 【list合并】多个list合并为一个list
- Polygon zkEVM工具——PIL和CIRCOM
- Golang分布式应用之etcd
- 娄底石油化工实验设计、建设规划概述
猜你喜欢
随机推荐
mSystems | 中农汪杰组揭示影响土壤“塑料际”微生物群落的机制
Pod生命周期
专有云ABC Stack,真正的实力派!
Overseas media publicity. What problems should domestic media pay attention to?
kubernetes介绍
wirshark 常用操作及 tcp 三次握手过程实例分析
【iOS】面试整理
【百度统计】用户行为分析
娄底疾控中心实验室设计理念说明
StarRocks on AWS 回顾 | Data Everywhere 系列活动深圳站圆满结束
ASP.NET Core依赖注入系统学习教程:ServiceDescriptor(服务注册描述类型)
海外媒体宣发.国内媒体发稿要注意哪些问题?
如何让别人看不懂你的 JS 代码?把你当大佬!
动态规划之最长回文子串
Merge similar items in LeetCode simple questions
MySQL面试题——MySQL常见查询
Solve the idea that unit tests cannot use Scanner
[Collection] HashSet and ArrayList lookup Contains() time complexity
The god-level Alibaba "high concurrency" tutorial - basic + actual combat + source code + interview + architecture is all-inclusive
Excel function formulas - LOOKUP function