当前位置:网站首页>【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
边栏推荐
- FPGA - Memory Resources of 7 Series FPGA Internal Structure -03- Built-in Error Correction Function
- 12 Recurrent Neural Network RNN2 of Deep Learning
- Shell编程规范与变量
- c语言之 练习题1 大贤者福尔:魔法数,神奇的等式
- 【PCBA solution】Electronic grip strength tester solution she'ji
- 力扣221题,最大正方形
- Service - DNS forward and reverse domain name resolution service
- Live Classroom System 08-Tencent Cloud Object Storage and Course Classification Management
- 如何保护 LDAP 目录服务中的用户安全?
- 这些不可不知的JVM知识,我都用思维导图整理好了
猜你喜欢
异常的了解
Service - DHCP principle and configuration
These must-know JVM knowledge, I have sorted it out with a mind map
Live Classroom System 08-Tencent Cloud Object Storage and Course Classification Management
为什么一般公司面试结束后会说「回去等消息」,而不是直接告诉面试者结果?
C # Hex file transfer skills necessary article 】 【 bin file code implementation
一篇文章教你Pytest快速入门和基础讲解,一定要看
LeetCode-36-二叉搜索树与双向链表
玩转doxygen 之RT-THREAD
解码2022中国网安强星丨正向建、反向查,华为构建数字化时代的网络安全防线
随机推荐
c语言之 练习题1 大贤者福尔:魔法数,神奇的等式
RTL8721DM 双频WIFI + 蓝牙5.0 物联网(IoT)应用
FPGA - 7系列 FPGA内部结构之Memory Resources -03- 内置纠错功能
【Maui正式版】创建可跨平台的Maui程序,以及有关依赖注入、MVVM双向绑定的实现和演示
一篇文章教你Pytest快速入门和基础讲解,一定要看
直播课堂系统09--腾讯云点播管理模块(一)
美味的佳肴
HighTec shortcut keys (Keys) setting location
阿里巴巴、蚂蚁集团推出分布式数据库 OceanBase 4.0,单机部署性能超 MySQL
自组织是管理者和成员的双向奔赴
LeetCode-402 - Remove K digits
扩展中国剩余定理
shell (text printing tool awk)
水果沙拉酱
shell(文本打印工具awk)
mmpose关键点(一):评价指标(PCK,OKS,mAP)
“数据引擎”开启前装规模量产新赛道,「智协慧同」崭露头角
QT笔记——用VS + qt 生成dll 和 调用生成的dll
QT笔记——QT工具uic,rcc,moc,qmake的使用和介绍
2022.8.9 Mock Competition