aboutsummaryrefslogtreecommitdiffstats
path: root/67/main.go
blob: 4cafdcfe6dcb1ee8e37d0d4228700063382b5a9b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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"))
}