Implement a basic calculator to evaluate a simple expression string.The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
思路
拿到第一個(gè)數(shù)
拿到第一個(gè)操作符
拿到第二個(gè)數(shù)
根據(jù)操作符類型進(jìn)行判斷。如果是乘除對(duì)num進(jìn)行更新,如果是加減,對(duì)最終結(jié)果res進(jìn)行更新,并更新運(yùn)算符。
判斷最后一個(gè)運(yùn)算符,如果是加減更新res
public class Solution {
public int calculate(String s) {
int res = 0, num = 0;
int index = 0;
char symbol = '+';
int len = s.length();
while(index < len && s.charAt(index) == ' ' ) {
index++;
}
while(index < len && isDigit(s.charAt(index))) {
num = num * 10 + (s.charAt(index++) - '0');
}
while(index < len){
if (index < len && s.charAt(index) == ' ' ) {
index++;
continue;
}
char symbol1 = s.charAt(index++);
int tmp = 0;
while(index < len && s.charAt(index) == ' ' ) {
index++;
}
while(index < len && isDigit(s.charAt(index))) {
tmp = tmp * 10 + (s.charAt(index++) - '0');
}
if (symbol1 == '+' || symbol1 == '-') {
if (symbol == '+'){
res += num;
}else {
res -= num;
}
num = tmp;
symbol = symbol1;
} else {
if (symbol1 == '*') {
num *= tmp;
} else {
num /= tmp;
}
}
}
if (symbol == '+') {
res += num;
} else {
res -= num;
}
return res;
}
private final boolean isDigit(char s) {
return s >= '0' && s <= '9';
}
}
最后編輯于 :2017.12.06 00:22:22
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者 平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。