java代码实现输入一个字符串多项式:3x^2 + 3x + 2^2 - 2x + 6xy + 5*6 + y^6 - 6yx, 合并同类项项后,降幂输出
时间: 2023-06-04 07:05:07 浏览: 119
好的,根据你的要求,这是一个技术问题,可以回答。下面是Java代码实现输入一个字符串多项式,合并同类项并降幂输出的代码:
```
import java.util.*;
public class Polynomial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] poly = sc.nextLine().split("\\s+");
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < poly.length; i++) {
String[] term = poly[i].split("(?=\\w)");
int coef = Integer.parseInt(term[0]);
if (term.length == 1) {
if (map.containsKey("")) {
map.put("", map.get("") + coef);
} else {
map.put("", coef);
}
} else {
String key = term[1].replaceAll("\\^", "");
if (map.containsKey(key)) {
map.put(key, map.get(key) + coef);
} else {
map.put(key, coef);
}
}
}
List<String> result = new ArrayList<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getKey().isEmpty()) {
if (entry.getValue() != 0) {
result.add(Integer.toString(entry.getValue()));
}
} else {
if (entry.getValue() != 0) {
result.add(entry.getValue() + entry.getKey());
}
}
}
if (result.isEmpty()) {
System.out.println("0");
} else {
Collections.sort(result, new Comparator<String>() {
public int compare(String s1, String s2) {
String[] term1 = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
String[] term2 = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
int exponent1 = term1.length == 1 ? 0 : Integer.parseInt(term1[1]);
int exponent2 = term2.length == 1 ? 0 : Integer.parseInt(term2[1]);
return exponent2 - exponent1;
}
});
System.out.println(String.join(" ", result));
}
}
}
```
你可以将多项式输入到程序的标准输入中,然后程序会将多项式合并同类项,降幂输出。请注意,多项式中的项必须按照规定的格式输入,否则程序可能无法正确处理。
阅读全文