[LeetCode By Go 62]415. Add Strings

题目

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

解题思路

从低位往上加,注意进位
边界条件比较多,写个测试会好很多

代码

addStrings.go

package _415_Add_Strings

import (
    "strconv"
)


func AddStrings(num1 string, num2 string) string {
    len1 := len(num1)
    len2 := len(num2)
    var ret string
    var carry int
    var digit int

    for i, j := len1, len2; i > 0 || j > 0 || carry > 0; {
        digit = carry
        if i > 0 {
            i--
            digit += int(num1[i] - '0')
        }
        if j > 0 {
            j--
            digit += int(num2[j] - '0')
        }

        if digit > 9 {
            carry = 1
        } else {
            carry = 0
        }

        ret = strconv.Itoa(digit % 10) + ret
    }

    return ret
}

测试

addStrings_test.go

package _415_Add_Strings

import "testing"

func TestAddStrings(t *testing.T) {
    var tests = []struct{
        num1 string
        num2 string
        output string
    }{
        {"0", "0", "0"},
        {"1", "2", "3"},
        {"123", "12", "135"},
    }

    for _, v := range tests {
        ret := AddStrings(v.num1, v.num2)

        if ret == v.output {
            t.Logf("pass")
        } else {
            t.Errorf("fail, want %+v, get %+v", v.output, ret)
        }
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/4dc8defd9d5a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞