美文网首页LeetCode By Go
[LeetCode By Go 22]Add to List 3

[LeetCode By Go 22]Add to List 3

作者: miltonsun | 来源:发表于2017-08-18 11:25 被阅读3次

    题目

    Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

    Example:
    Given a = 1 and b = 2, return 3.

    解题思路

    不能使用+,-操作符,可以使用++,--操作符啊,一个个加上去或者减下来,可以找出绝对值较小的那个减少加减的次数,就算不找,int加减个几万次也没啥影响。

    代码

    getSum.go

    package _371_Sum_of_Two_Integers
    
    func GetSum(a int, b int) int {
        if a < 0 && b < 0 {
            if a > b {
                a, b = b, a
            }
        } else if a > 0 && b < 0 {
            if a < -b {
                a, b = b, a
            }
        } else if a < 0 && b > 0 {
            if a < b {
                a, b = b, a
            }
        }
    
    
        if b > 0 {
            for i := 0; i < b; i++ {
                a++
            }
        } else {
            for i := b; i < 0; i++ {
                a--
            }
        }
    
    
        return a
    }
    

    测试

    getSum_test.go

    package _371_Sum_of_Two_Integers
    
    import "testing"
    
    func TestGetSum(t *testing.T) {
        var tests = []struct {
            a int
            b int
            output int
        }{
            {1, 2, 3},
            {1, -1, 0},
        }
    
        for _, test := range tests {
            ret := GetSum(test.a, test.b)
            if ret == test.output {
                t.Logf("pass")
            } else {
                t.Errorf("fail, want %+v, get %+v", test.output, ret)
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 22]Add to List 3

        本文链接:https://www.haomeiwen.com/subject/owaorxtx.html