Skip to content

Add: Add Strings #654

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 11 additions & 13 deletions problems/add-binary/add_binary.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
package add_binary
package problem_67

func addBinary(a string, b string) string {
i, j := len(a)-1, len(b)-1
var carry byte = '0'
var bs []byte
for i >= 0 || j >= 0 || carry != '0' {
ans, l1, l2, carry := "", len(a)-1, len(b)-1, byte('0')
for l1 >= 0 || l2 >= 0 || carry != '0' {
v := carry
if i >= 0 {
v += a[i] - '0'
i--
if l1 >= 0 {
v += a[l1] - '0'
l1--
}
if j >= 0 {
v += b[j] - '0'
j--
if l2 >= 0 {
v += b[l2] - '0'
l2--
}
carry = '0' + (v-'0')/2
v = '0' + (v-'0')%2
bs = append([]byte{v}, bs...)
ans = string(v) + ans
}
return string(bs)
return ans
}
2 changes: 1 addition & 1 deletion problems/add-binary/add_binary_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package add_binary
package problem_67

import "testing"

Expand Down
21 changes: 20 additions & 1 deletion problems/add-strings/add_strings.go
Original file line number Diff line number Diff line change
@@ -1 +1,20 @@
package add_strings
package problem_415

func addStrings(num1 string, num2 string) string {
ans, l1, l2, carry := "", len(num1)-1, len(num2)-1, byte('0')
for l1 >= 0 || l2 >= 0 || carry != '0' {
v := carry
if l1 >= 0 {
v += num1[l1] - '0'
l1--
}
if l2 >= 0 {
v += num2[l2] - '0'
l2--
}
carry = '0' + (v-'0')/10
v = '0' + (v-'0')%10
ans = string(v) + ans
}
return ans
}
41 changes: 40 additions & 1 deletion problems/add-strings/add_strings_test.go
Original file line number Diff line number Diff line change
@@ -1 +1,40 @@
package add_strings
package problem_415

import "testing"

type caseType struct {
num1 string
num2 string
expected string
}

func TestAddStrings(t *testing.T) {
tests := [...]caseType{
{
num1: "0",
num2: "0",
expected: "0",
},
{
num1: "1",
num2: "2",
expected: "3",
},
{
num1: "9",
num2: "9",
expected: "18",
},
{
num1: "100",
num2: "999",
expected: "1099",
},
}
for _, tc := range tests {
output := addStrings(tc.num1, tc.num2)
if output != tc.expected {
t.Fatalf("input: %v, output: %v, expected: %v", tc, output, tc.expected)
}
}
}