[LeetCode By Go 22]Add to List 371. Sum of Two Integers

题目

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)
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容