LintCode: Simple Calculator

Simple Calculator



Similar Problems:


Follow-up:
- What if a*b is bigger than MAX_INT?
- What if 5/0?

Description

Given two integers a and b, an operator, choices:

+, -, *, /

Calculate a <operator> b.

Use switch grammar to solve it

Example

For a = 1, b = 2, operator = +, return 3.

For a = 10, b = 20, operator = *, return 200.

For a = 3, b = 2, operator = /, return 1. (not 1.5)

For a = 10, b = 11, operator = -, return -1.

Github: code.dennyzhang.com

Credits To: lintcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// Blog link: https://code.dennyzhang.com/simple-calculator
// Basic Ideas:
// Here we assume no case of "X / 0"
// Complexity: Time O(1), Space O(1)
/**
 * @param a: An integer
 * @param operator: A character, +, -, *, /.
 * @param b: An integer
 * @return: The result
 */
func calculate (a int, operator byte, b int) int {
    res := 0
    switch operator {
        case '+':
            res = a+b
        case '-':
            res = a-b
        case '/':
            res = a/b
        case '*':
            res = a*b        
    }
    return res
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.