File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "fmt"
5
+ "strconv"
6
+ "strings"
7
+ )
8
+
9
+ func addBinary (a string , b string ) string {
10
+ if len (a ) < len (b ) {
11
+ a , b = b , a
12
+ }
13
+ temp := []string {}
14
+ for _ , v := range a [:len (a )- len (b )] {
15
+ temp = append (temp , string (v ))
16
+ }
17
+ for i , _ := range b {
18
+ temp = append (temp , string (a [len (a )- len (b ):][i ]+ b [i ]- '0' ))
19
+ }
20
+ for i := len (temp ) - 1 ; i > 0 ; i -- {
21
+ cur , _ := strconv .Atoi (temp [i ])
22
+ if cur > 1 {
23
+ pre , _ := strconv .Atoi (temp [i - 1 ])
24
+ temp [i - 1 ] = fmt .Sprintf ("%d" , pre + cur / 2 )
25
+ temp [i ] = fmt .Sprintf ("%d" , cur % 2 )
26
+ }
27
+ }
28
+ first , _ := strconv .Atoi (temp [0 ])
29
+ if first > 1 {
30
+ temp [0 ] = fmt .Sprintf ("%d" , first % 2 )
31
+ newTemp := []string {}
32
+ newTemp = append (newTemp , fmt .Sprintf ("%d" , first / 2 ))
33
+ newTemp = append (newTemp , temp ... )
34
+ temp = newTemp
35
+ }
36
+ return strings .Join (temp , "" )
37
+ }
38
+
39
+ func main () {
40
+ // fmt.Println(addBinary("111", "11111"))
41
+ // fmt.Println(addBinary("1010", "1011"))
42
+ fmt .Println (addBinary ("100" , "110010" ))
43
+ }
You can’t perform that action at this time.
0 commit comments