diff options
author | terminaldweller <thabogre@gmail.com> | 2023-02-14 08:44:05 +0000 |
---|---|---|
committer | terminaldweller <thabogre@gmail.com> | 2023-02-14 08:44:05 +0000 |
commit | 60ec46e8b0899c0cf936d7515157adc12ef728ba (patch) | |
tree | 839e8cc40a5eb5088bb2e9d3b98406a2cb312066 | |
parent | 790 (diff) | |
download | leetcode-60ec46e8b0899c0cf936d7515157adc12ef728ba.tar.gz leetcode-60ec46e8b0899c0cf936d7515157adc12ef728ba.zip |
67
-rw-r--r-- | 67/go.mod | 3 | ||||
-rw-r--r-- | 67/main.go | 72 |
2 files changed, 75 insertions, 0 deletions
diff --git a/67/go.mod b/67/go.mod new file mode 100644 index 0000000..4b89718 --- /dev/null +++ b/67/go.mod @@ -0,0 +1,3 @@ +module 67 + +go 1.19 diff --git a/67/main.go b/67/main.go new file mode 100644 index 0000000..4cafdcf --- /dev/null +++ b/67/main.go @@ -0,0 +1,72 @@ +package main + +import "fmt" + +func addBinary(a string, b string) string { + var long string + var short string + var count int + carry := false + + if len(a) >= len(b) { + long = a + short = b + } else { + long = b + short = a + } + + result := make([]byte, len(long)+1) + + for i := len(long) - 1; i >= 0; i-- { + if long[i] == '1' { + count++ + } + + if len(short)-(len(long)-i) >= 0 { + if short[len(short)-(len(long)-i)] == '1' { + count++ + } + } + + if carry { + count++ + } + + switch count { + case 0: + result[i+1] = '0' + carry = false + case 1: + result[i+1] = '1' + carry = false + case 2: + result[i+1] = '0' + carry = true + case 3: + result[i+1] = '1' + carry = true + } + + count = 0 + } + if carry { + result[0] = '1' + } + + // fmt.Println(result) + if result[0] == 0 { + return string(result[1:]) + } else { + return string(result) + } +} + +func main() { + fmt.Println(addBinary("11", "1")) + fmt.Println(addBinary("1010", "1011")) + fmt.Println(addBinary("0111", "0111")) + fmt.Println(addBinary("0", "0")) + fmt.Println(addBinary("10", "0")) + fmt.Println(addBinary("10", "1")) +} |