gpt4 book ai didi

java - 在不使用正则表达式和 API 的情况下评估多项式字符串

转载 作者:搜寻专家 更新时间:2023-10-31 20:12:34 25 4
gpt4 key购买 nike

给定一个包含单个变量 x 的多项式,并将 x 的值作为输入,计算它的值。示例:

eval("-2x^3+10x-4x^2","3")=-60

eval("x^3+x^2+x","6")=258

问题描述:在这段代码中,每当遇到 +/- 时,我都会将字符串分解为一个子字符串,并将该子字符串传递给一个函数,该函数计算单个项,如“-2x^3”。所以我的输入代码 = "-2x^3+10x-4x^2"只计算到​​ "-2x^3+10x"并跳过 "-4x^2"部分。

谁能告诉我这里有什么问题吗?

public class EvalPolyX2 {

static String testcase1 = "-2x^3+10x-4x^2";
static String testcase2 = "3";

public static void main(String args[]){
EvalPolyX2 testInstance = new EvalPolyX2();
int result = testInstance.eval(testcase1,testcase2);
System.out.println("Result : "+result);
}

public int eval(String str,String valx){

int sum = 0;
String subStr = "";
if(str.charAt(0) == '-')
{
int len = str.length();
for (int i = 0; i < len; i++)
{
if(str.charAt(i) == '-' || str.charAt(i) == '+')
{
subStr = str.substring(0, i);
System.out.println("subStr="+subStr);
sum += evalSubPoly(subStr, valx);
str = str.substring(i);
len = str.length();
i = 0;
}
}
}
else if(str.charAt(0) != '-')
{
str = '+' + str;
int len = str.length();
for (int i = 0; i < len; i++)
{
if(str.charAt(i) == '-' || str.charAt(i) == '+')
{
subStr = str.substring(0, i);
System.out.println("subStr="+subStr);
sum += evalSubPoly(subStr, valx);
str = str.substring(i);
len = str.length();
i=0;
}
}
}
return sum;
}

public int evalSubPoly(String poly,String valx){
int len = poly.length();
String num = "";
String power = "";
int exp = 0, coeff = 0;

for(int i = 0; i < len; i++)
{
if(poly.charAt(i) == 'x')
{
num = poly.substring(0, i);
coeff = Integer.parseInt(num);
}
if(poly.charAt(i) == '^')
{
power = poly.substring(i+1, len);
exp = Integer.parseInt(power);
}
}

if(power.equals(""))
exp = 1;
System.out.println("coeff="+coeff);

int sum = 1;
int x = Integer.parseInt(valx);

for (int i = 0; i < exp; i++)
{
sum = sum*x;
}
System.out.println("sum="+sum);
sum = sum*coeff;

return sum;
}
}

最佳答案

使用正则表达式有什么问题?您可以将多项式拆分为单项式,计算每个单项式,然后将所有结果相加。

private static final Pattern monomial = Pattern
.compile("([+-])?(\\d+)?x(?:\\^(\\d+))?");

public static int eval(String str, String valx) {
Matcher m = monomial.matcher(str);
int x = Integer.parseInt(valx);

int total = 0;
while (m.find()) {
String mul = m.group(2);
int value = (mul == null) ? 1 : Integer.parseInt(m.group(2));

String pow = m.group(3);
value *= (pow == null) ? x : (int) Math.pow(x,
Integer.parseInt(pow));

if ("-".equals(m.group(1)))
value = -value;

total += value;
}

return total;
}

System.out.println(eval("-2x^3+10x-4x^2", "3"));
System.out.println(eval("x^3+x^2+x", "6"));
-60258

关于java - 在不使用正则表达式和 API 的情况下评估多项式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18386403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com