当前位置:网站首页>力扣解法汇总640-求解方程
力扣解法汇总640-求解方程
2022-08-10 13:30:00 【失落夏天】
目录链接:
力扣编程题-解法汇总_分享+记录-CSDN博客
GitHub同步刷题项目:
https://github.com/September26/java-algorithms
原题链接:
描述:
求解一个给定的方程,将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' 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/solve-the-equation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
* 解题思路: * 分解字符串,用四个变量来记录,左边x的数量(xLeftNum),左边常数的值(valueLeftNum),右边x的数量(xRightNum),右边常数的值(valueRightNum), * 如果xLeftNum==xRightNum时,valueLeftNum=valueRightNum就是无限解,否则就是没有解。 * 如果xLeftNum!=xRightNum时,x=(valueLeftNum - valueRightNum) / (xRightNum - xLeftNum)
代码:
public class Solution640 {
public String solveEquation(String equation) {
String[] split = equation.split("=");
Pair<Integer, Integer> pairLeft = getXAndValueNum(split[0]);
Pair<Integer, Integer> pairRight = getXAndValueNum(split[1]);
int xLeftNum = pairLeft.getKey();
int valueLeftNum = pairLeft.getValue();
int xRightNum = pairRight.getKey();
int valueRightNum = pairRight.getValue();
if (xLeftNum != xRightNum) {
return "x=" + (valueLeftNum - valueRightNum) / (xRightNum - xLeftNum);
}
if (valueLeftNum == valueRightNum) {
return "Infinite solutions";
}
return "No solution";
}
private Pair<Integer, Integer> getXAndValueNum(String str) {
int xNum = 0;
int valueNum = 0;
boolean isPositive = true;
StringBuilder builder = new StringBuilder();
int index = 0;
char[] chars = str.toCharArray();
while (index++ < str.length()) {
char aChar = 0;
aChar = chars[index - 1];
if (aChar != '-' && aChar != '+') {
builder.append(aChar);
if (index < str.length()) {
continue;
}
}
String currentValue = builder.toString();
builder.setLength(0);
int num;
if (!currentValue.endsWith("x")) {
if (currentValue.length() == 0) {
num = 0;
} else {
num = Integer.parseInt(currentValue);
}
if (isPositive) {
valueNum += num;
} else {
valueNum -= num;
}
isPositive = aChar == '+';
continue;
}
String substring = currentValue.substring(0, currentValue.length() - 1);
if (substring.length() == 0) {
num = 1;
} else {
num = Integer.parseInt(substring);
}
if (isPositive) {
xNum += num;
} else {
xNum -= num;
}
isPositive = aChar == '+';
}
return new Pair<>(xNum, valueNum);
}
}
边栏推荐
- vue 怎么清除tab 切换缓存问题 ?
- [target detection] small script: extract training set images and labels and update the index
- BEVDet4D: Exploit Temporal Cues in Multi-camera 3D Object Detection 论文笔记
- 需要被记录的OpenStack相关的命令_自己用
- 【JS高级】ES5标准规范之创建子对象以及替换this_10
- 用低代码驱动IT现代化
- 山水的高度
- How to describe multiple paragraphs with different font settings in Open Office XML format
- Import other custom namespaces in C#
- 神经网络可视化有3D版本了,美到沦陷!(已开源)
猜你喜欢
ABAP file operations involved in the Chinese character set of problems and solutions for trying to read
M²BEV: Multi-Camera Joint 3D Detection and Segmentation with Unified Bird’s-Eye View Representation
神经网络可视化有3D版本了,美到沦陷!(已开源)
第三方软件测评有什么作用?权威软件检测机构推荐
广东10个项目入选工信部2021年物联网示范项目名单
mSystems | Zhongnong Wang Jie Group Reveals the Mechanisms Affecting Soil "Plastic Interstitial" Microbial Communities
日志@Slf4j介绍使用及配置等级
bgp双平面实验 路由策略控制流量
2022-08-09: What does the following go code output?A: No, it will panic; B: Yes, it can run correctly; C: Not sure, see the voting result.package main import (“fmt“ “syn
Ethernet channel Ethernet channel
随机推荐
Vivado crashes or the message is not displayed
系统的安全和应用(不会点安全的东西你怎么睡得着?)
数据产品经理那点事儿 二
Makefile missing separator. Stop.怎么解决「建议收藏」
I would like to ask the big guys, how to solve this error when cdc oracle initializes a 3 million table task running
Fragment's show and hide
C# WPF image is displayed without problems, but the solution does not display the image at runtime
R语言使用gt包和gtExtras包优雅地、漂亮地显示表格数据:gtExtras包的gt_highlight_rows函数高亮(highlight)表格中特定的数据行、配置高亮行的特定数据列数据加粗
Efficient and Robust 2D-to-BEV Representation Learning via Geometry-guided Kernel Transformer 论文笔记
Loudi Center for Disease Control and Prevention Laboratory Design Concept Description
2022-08-09: What does the following go code output?A: No, it will panic; B: Yes, it can run correctly; C: Not sure, see the voting result.package main import (“fmt“ “syn
神经网络可视化有3D版本了,美到沦陷!(已开源)
【ECCV 2022|Millions of Prizes】PSG Competition: Pursuing the "Most Comprehensive" Scene Understanding
【MinIO】Using tools
作业8.9 构建TCP协议的服务器
Error: Rule can only have one resource source (provided resource and test + include + exclude)
SenseTime self-developed robotic arm, the first product is an AI chess-playing robot: Guo Jingjing is also invited as an endorsement
[Study Notes] Persistence of Redis
学习日记8
ES5和SE6来实现一个Promise效果