[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)
        }
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/d8efe9b7693b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞