gpt4 book ai didi

java - 求解表达式的输出未按预期输出

转载 作者:行者123 更新时间:2023-11-30 07:44:00 25 4
gpt4 key购买 nike

Given a string representing a simple arithmetic expression, solve it and return its integer value. The expression consists of two numbers with a + or – operator between the numbers, i.e., it will of the form x+y or x-y where x and y are not negative

我的方法

我创建了 NewString 并存储了第一个字符串,直到运算符不出现。我将运算符放在字符位置。我创建了第二个字符串并将其余字符串存储到新 String 中。然后将它们转换为使用 parseInt 进行数字。然后我添加了数字。

我想做什么123+82=205

我正在做123+43+82=248。我不知道如何定位角色。

Can anyone guide me what I am doing wrong?

public int solve(String str)
{
String strnew1="";
String strnew2="";
int i=0;
char ch1=str.charAt(i);
while((ch1>=48)&&(ch1<=57))
{
strnew=strnew+ch1;
i++;
}
int p=str.charAt(i);
i++;

while((ch1>=48)&&(ch1<=57))
{
strnew2=strnew2+ch1;
i++;
if(i==str.length())
{
break;
}


}
int n1=Integer.parseInt(strnew1);
int n2=Integer.parseInt(strnew2);
n1=n1+p+n2;
return n1;

}

测试用例结果。

  Parameters          Actual Output   ExpectedOutput

123+82 248 205

最佳答案

这是完成任务的好方法。基本上,您会进行迭代,直到找到“+”r“-”符号,同时将字符附加到字符串中。现在维护一个 boolean 值,它告诉您添加或减去并在到达符号时设置该值。现在,迭代运算符符号并将字符附加到另一个字符串。最后,将它们解析为整数,进行加/减并返回结果。

 public static int Solve(String input) //Assume input="100+50" for eg.
{
int cnt=0;
boolean op=false; //Default set to subtract
String raw_a="", raw_b="";
while(input.charAt(cnt)!='+')
raw_a+=input.charAt(cnt++); //The first part
if(input.charAt(cnt)=='+') //setting the operation
op=true;
cnt++;
while(cnt!=input.length())
raw_b+=input.charAt(cnt++); //the second part
int a=Integer.parseInt(raw_a), b=Integer.parseInt(raw_b); //parsing them
int ans =op? a+b: a-b; //If true then add else subtract
return ans; //Return the ans
}

关于java - 求解表达式的输出未按预期输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34196216/

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