ðŸ¥ˆ

# Basic Calculator II

Created
2021/12/25 02:30
ë¬¸ì œ ë²ˆí˜¸
227
ì¹´í…Œê³ ë¦¬
Math
String
Stack

### Code

 .css-15tnwsa{max-width:100%;width:100%;white-space:pre-wrap;word-break:break-word;padding:7px 9px;background-color:transparent;font-size:14px;line-height:20px;min-height:1em;}.css-15tnwsa:empty::after{content:" ";}ì œì¶œ ë‚ ì§œ ì‹œê°„ ë©”ëª¨ë¦¬ 2021/12/25 0 ms 2.8 MB
// 227. Basic Calculator II // // https://leetcode.com/problems/basic-calculator-ii/ // strings package is used for replacing spaces to nothing. // unicode package is used for checking the rune is digit or not. import ( "strings" "unicode" ) // calculate function calculates the given string expression. // Only "+", "-", "*", "/" operators are allowed. // As many spaces as possible between operands and operators. // Such a simple calculating does not require the stack operation. func calculate(s string) int { num, temp, res, lastOperator := 0, 0, 0, '+' strings.Replace(s, " ", "", -1) for i, char := range s { if unicode.IsDigit(char) { num = num*10 + (int(char - '0')) } if i == len(s)-1 || char == '+' || char == '-' || char == '*' || char == '/' { switch lastOperator { case '+': res += temp temp = num case '-': res += temp temp = -num case '*': temp *= num case '/': temp /= num } num = 0 lastOperator = char } } res += temp return res }
Go
ë³µì‚¬