67.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package main
  2. // add binary
  3. // func minInt(x, y int) int {
  4. // if x < y {
  5. // return x
  6. // }
  7. // return y
  8. // }
  9. const one, zero = byte('1'), byte('0')
  10. func add3Bi(x, y, z byte) (sum, remain byte) {
  11. switch x + y + z - 3*zero {
  12. case 0:
  13. return zero, zero
  14. case 1:
  15. return one, zero
  16. case 2:
  17. return zero, one
  18. case 3:
  19. return one, one
  20. default:
  21. return
  22. }
  23. }
  24. func reverseStr(s string) string {
  25. runes := []rune(s)
  26. for from, to := 0, len(s)-1; from < to; from, to = from+1, to-1 {
  27. runes[from], runes[to] = runes[to], runes[from]
  28. }
  29. return string(runes)
  30. }
  31. func addBinary(a string, b string) string {
  32. la, lb := len(a)-1, len(b)-1
  33. sum, remain := zero, zero
  34. res := make([]rune, 0)
  35. for i := 0; i <= minInt(la, lb); i++ {
  36. sum, remain = add3Bi(a[la-i], b[lb-i], remain)
  37. res = append(res, rune(sum))
  38. }
  39. lc := 0
  40. var c string
  41. if la < lb {
  42. c = b
  43. lc = lb
  44. } else {
  45. c = a
  46. lc = la
  47. }
  48. for i := minInt(la, lb) + 1; i <= lc; i++ {
  49. sum, remain = add3Bi(zero, c[lc-i], remain)
  50. res = append(res, rune(sum))
  51. }
  52. if remain == one {
  53. res = append(res, rune(one))
  54. }
  55. return reverseStr(string(res))
  56. }