我在面試中遇到了這個問題,回傳這個 String s = "4 8×2" , output = 20, Ex2: String s = "3×7-4", output = 17的輸出。這是我的方法,但我無法得到預期的結果,請在此處指出正確的方法。
public static int findResult (String s) {
int i = 0;
Stack<String> stack = new Stack<>();
while (i < s.length()) {
if (s.charAt(i) == ' ') {
stack.push(String.valueOf(s.charAt(i)));
i ;
} else if (s.charAt(i) == '*') {
stack.push(String.valueOf(s.charAt(i)));
i ;
} else if (s.charAt(i) == '-') {
stack.push(String.valueOf(s.charAt(i)));
i ;
} else if (Character.isDigit(s.charAt(i))) {
int num = s.charAt(i) - '0';
while (i 1 < s.length() && Character.isDigit(s.charAt(i 1))) {
num = num * 10 s.charAt( i) - '0';
}
stack.push(String.valueOf(num));
i ;
}
}
int current = 0;
//second while loop
while (!stack.isEmpty()) {
int firstNumber = Integer.parseInt(stack.pop());
if (stack.isEmpty()) return current;
String sign = stack.pop(""
//int firstNum = Integer.parseInt(stack.pop());
if (sign.equals("*")) {
current = firstNumber * Integer.parseInt(stack.pop());
stack.push(String.valueOf(current));
}
else if (sign.equals("-")) {
current = firstNumber;
stack.push(String.valueOf(current));
} else {
current = firstNumber Integer.parseInt(stack.pop());
stack.push(String.valueOf(current));
}
}
return Integer.parseInt(stack.pop());
}
uj5u.com熱心網友回復:
這就是我解決這個問題的方式。(這和你的有點相似)。我先貼出代碼,然后解釋下面的程序:
import java.util.*;
class Main {
public static void main(String[] args) {
System.out.println(findResult("2*57-38*3/5-5-2 3*4/2-2-2"));
}
public static double findResult (String s){
String sub = s;
ArrayList<Double> nums = new ArrayList<Double>();
ArrayList<Character> operations = new ArrayList<Character>();
for(int x = 0; x < s.length(); x ){
if(s.charAt(x) == ' ' || s.charAt(x) == '-' || s.charAt(x) == '*' || s.charAt(x) == '/' ){
operations.add(s.charAt(x));
int subInd = sub.indexOf(s.charAt(x));
nums.add(Double.valueOf(sub.substring(0,subInd)));
sub = sub.substring(subInd 1);
}
}
nums.add(Double.valueOf(sub));
String[] operationTypes = {"*/"," -"};
for(int i = 0; i < 2; i ){
for(int j = 0; j < operations.size(); j ){
if(operationTypes[i].indexOf(operations.get(j)) != -1){
double val;
if(operations.get(j) == '*'){
val = nums.get(j) * nums.get(j 1);
}
else if(operations.get(j) == '/'){
val = nums.get(j) / nums.get(j 1);
}
else if(operations.get(j) == ' '){
val = nums.get(j) nums.get(j 1);
}
else{
val = nums.get(j) - nums.get(j 1);
}
nums.set(j,val);
nums.remove(j 1);
operations.remove(j);
j--;
}
}
}
return nums.get(0);
}
}
是的……很多:
此程序的第一步是將 String 分為兩個ArrayLists:nums和operations. nums存盤術語并operations存盤..操作(*、/、 、-)。
現在,我們遍歷每個“組”操作,即乘法和除法,加法和減法。
從 mult/div 開始,如果我們在我們的 中看到 a'*'或,那么我們計算我們中相應元素的乘積或商,并通過修改與操作匹配索引的元素并洗掉它后面的術語來進行相應的編輯。確保您還從 nums 中洗掉了該操作并減少了 counter 變數,這樣回圈就不會跳過任何值。'/'operationsnumsnums
Finally, we will return the only value left in our nums which will be our answer.
I hope this helped you! Please let me know if you need any further details or clarification :)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433690.html
下一篇:為什么替換所有方法不起作用?
