-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy path1073.Adding-Two-Negabinary-Numbers.go
More file actions
66 lines (56 loc) · 1.01 KB
/
1073.Adding-Two-Negabinary-Numbers.go
File metadata and controls
66 lines (56 loc) · 1.01 KB
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
// https://leetcode.com/problems/adding-two-negabinary-numbers/
//
// algorithms
// Medium (26.02%)
// Total Accepted: 1,239
// Total Submissions: 4,762
// beats 100.0% of golang submissions
package leetcode
func addNegabinary(arr1 []int, arr2 []int) []int {
len1, len2 := len(arr1), len(arr2)
var idx1, idx2 int
var res []int
var carry int
sample := -1
for i := 1; i <= max(len1, len2); i++ {
idx1 = len1 - i
idx2 = len2 - i
bit := carry * sample
if idx1 >= 0 {
bit += arr1[idx1]
}
if idx2 >= 0 {
bit += arr2[idx2]
}
if bit > 0 {
carry = bit / 2
res = append([]int{bit % 2}, res...)
sample = -1
} else if bit < 0 {
carry = 1
res = append([]int{1}, res...)
sample = 1
} else {
res = append([]int{0}, res...)
carry = 0
}
}
if carry != 0 {
res = append([]int{1, 1}, res...)
} else {
var i int
for ; i < len(res)-1; i++ {
if res[i] != 0 {
break
}
}
res = res[i:]
}
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}