Last active
May 17, 2020 08:39
-
-
Save Gasoid/0cfec724d8079233e3e73090b40bb815 to your computer and use it in GitHub Desktop.
sum of two large numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
reader := bufio.NewReader(os.Stdin) | |
line, _, _ := reader.ReadLine() | |
nums := strings.Split(string(line), " ") | |
num1 := nums[0] | |
num2 := nums[1] | |
result := addition(num1[:len(num1)], num2[:len(num2)]) | |
fmt.Print(result) | |
} | |
func addition(num1 string, num2 string) string { | |
nums := [2]string{num1, num2} | |
index0 := 0 | |
index1 := 1 | |
if len(num1) < len(num2) { | |
index0 = 1 | |
index1 = 0 | |
} | |
end1 := len(nums[index0]) - 1 | |
end2 := len(nums[index1]) - 1 | |
sum := []string{} | |
carry := 0 | |
for i := 0; i <= end1 || carry > 0; i++ { | |
num1 := 0 | |
num2 := 0 | |
if i <= end1 { | |
num1, _ = strconv.Atoi(string(nums[index0][end1-i])) | |
num2 = 0 | |
if i <= end2 { | |
num2, _ = strconv.Atoi(string(nums[index1][end2-i])) | |
} | |
} | |
s := num1 + num2 + carry | |
sum = append(sum, strconv.Itoa(s%10)) | |
carry = s / 10 | |
} | |
endSum := len(sum) | |
rSum := make([]string, endSum, endSum) | |
for i := 0; i < endSum; i++ { | |
rSum[i] = sum[endSum-i-1] | |
} | |
return strings.Join(rSum, "") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"math/rand" | |
"testing" | |
) | |
func TestAddition(t *testing.T) { | |
rand.Seed(5000) | |
for i := 0; i < 1000; i++ { | |
i1 := rand.Intn(100000) | |
i2 := rand.Intn(10000000) | |
result := addition(fmt.Sprint(i1), fmt.Sprint(i2)) | |
s := i1 + i2 | |
log.Printf("%v + %v = %v (%v)\n", i1, i2, s, result) | |
if result != fmt.Sprint(s) { | |
t.Errorf("result != sum => %v", s) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment