TypechoJoeTheme

IT技术分享

统计

[LeetCode 227] Basic Calculator II [Java]

2017-11-07
/
0 评论
/
870 阅读
/
正在检测是否收录...
11/07

1. Description

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.

Note: Do not use the eval built-in library function.

2. Example

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

3. Code

public class LeetCode0227 {
    public int calculate(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        int result = 0, record = 0, multOrDiv = 0, plusOrMinus = 1;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                int num = c - '0';
                for (i++; i < s.length() && Character.isDigit(s.charAt(i)); i++) {
                    num = num * 10 + s.charAt(i) - '0';
                }
                i--;
                if (multOrDiv == 1) {
                    record *= num;
                    multOrDiv = 0;
                } else if (multOrDiv == -1) {
                    if (num == 0) {
                        return 0;
                    } else {
                        record /= num;
                    }
                    multOrDiv = 0;
                } else {
                    record = num;
                }
            } else if (c == '*') {
                multOrDiv = 1;
            } else if (c == '/') {
                multOrDiv = -1;
            } else if (c == '+') {
                result += plusOrMinus * record;
                plusOrMinus = 1;
            } else if (c == '-') {
                result += plusOrMinus * record;
                plusOrMinus = -1;
            }
        }
        return result + plusOrMinus * record;
    }

    public static void main(String[] args) {
        LeetCode0227 leetcode = new LeetCode0227();
        System.out.println(leetcode.calculate("2*3+4"));
    }
}
String
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1247/(转载时请注明本文出处及文章链接)