当前位置:网站首页>【640. 求解方程】
【640. 求解方程】
2022-08-10 21:49:00 【千北@】
来源:力扣(LeetCode)
描述:
求解一个给定的方程,将 x
以字符串 "x=#value"
的形式返回。该方程仅包含 '+'
, '-'
操作,变量 x
和其对应系数。
如果方程没有解,请返回 "No solution"
。如果方程有无限解,则返回 “Infinite solutions”
。
题目保证,如果方程中只有一个解,则 'x'
的值是一个整数。
示例 1:
输入: equation = "x+5-3+x=6+x-2"
输出: "x=2"
示例 2:
输入: equation = "x=x"
输出: "Infinite solutions"
示例 3:
输入: equation = "2x=x"
输出: "x=0"
提示:
- 3 <= equation.length <= 1000
- equation 只有一个 ‘=’.
- equation 方程由整数组成,其绝对值在 [0, 100] 范围内,不含前导零和变量 ‘x’
方法:解析
代码:
class Solution {
public:
string solveEquation(string equation) {
int factor = 0, val = 0;
int index = 0, n = equation.size(), sign1 = 1; // 等式左边默认系数为正
while (index < n) {
if (equation[index] == '=') {
sign1 = -1; // 等式右边默认系数为负
index++;
continue;
}
int sign2 = sign1, number = 0;
bool valid = false; // 记录 number 是否有效
if (equation[index] == '-' || equation[index] == '+') {
// 去掉前面的符号
sign2 = (equation[index] == '-') ? -sign1 : sign1;
index++;
}
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";
}
return string("x=") + to_string(-val / factor);
}
};
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:5.9 MB, 在所有 C++ 提交中击败了83.55%的用户
复杂度分析
时间复杂度: O(n),其中 n 是字符串 equation 的长度。
空间复杂度: O(1)。
author:LeetCode-Solution
边栏推荐
- 阿里云新增三大高性能计算解决方案,助力生命科学行业快速发展
- unusual understanding
- 如何保护 LDAP 目录服务中的用户安全?
- 黑猫带你学Makefile第13篇:Makefile编译问题合集
- 华为HCIE云计算之Fusion Access桌面云
- 企业云存储日常运行维护实践经验分享
- 美创科技勒索病毒“零信任”防护和数据安全治理体系的探索实践
- Redis Performance Impact - Asynchronous Mechanisms and Response Latency
- An article to teach you a quick start and basic explanation of Pytest, be sure to read
- RK3399平台开发系列讲解(内核驱动外设篇)6.35、IAM20680陀螺仪介绍
猜你喜欢
xshell (sed 命令)
shell programming without interaction
Service - DNS forward and reverse domain name resolution service
ThreadLocal全面解析(一)
边缘与云计算:哪种解决方案更适合您的连接设备?
测试4年感觉和1、2年时没什么不同?这和应届生有什么区别?
【SQL刷题】Day3----SQL必会的常用函数专项练习
RK3399平台开发系列讲解(内核驱动外设篇)6.35、IAM20680陀螺仪介绍
shell编程之免交互
12 Recurrent Neural Network RNN2 of Deep Learning
随机推荐
QT笔记——vs + qt 创建一个带界面的 dll 和 调用带界面的dll
Live Classroom System 08-Tencent Cloud Object Storage and Course Classification Management
2022.8.8 Selected Lectures on Good Topics (Number Theory Field)
shell(文本打印工具awk)
TCP连接过程中如果拔掉网线会发生什么?
mmpose关键点(一):评价指标(PCK,OKS,mAP)
[SQL brush questions] Day3----Special exercises for common functions that SQL must know
Redis Performance Impact - Asynchronous Mechanisms and Response Latency
LeetCode-402 - Remove K digits
LeetCode每日一题(1573. Number of Ways to Split a String)
美味的石井饭
异常的了解
MySQL高级指令
labelme-屏蔽拖拽的事件
学会开会|成为有连接感组织的重要技能
APP UI自动化测试常见面试题,或许有用呢~
Play RT-THREAD of doxygen
服务——DNS正向反向域名解析服务
port forwarding
C # Hex file transfer skills necessary article 】 【 bin file code implementation