|
41 | 41 |
|
42 | 42 | <!-- 这里可写通用的实现逻辑 -->
|
43 | 43 |
|
| 44 | +模拟笔算加法的过程,注意进位 |
| 45 | + |
44 | 46 | <!-- tabs:start -->
|
45 | 47 |
|
46 | 48 | ### **Python3**
|
47 | 49 |
|
48 | 50 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
49 | 51 |
|
50 | 52 | ```python
|
51 | | - |
| 53 | +class Solution: |
| 54 | + def addBinary(self, a: str, b: str) -> str: |
| 55 | + x, y = len(a) - 1, len(b) - 1 |
| 56 | + arr = [] |
| 57 | + carry = 0 |
| 58 | + while x >= 0 or y >= 0: |
| 59 | + if x >= 0: |
| 60 | + if a[x] == '1': |
| 61 | + carry += 1 |
| 62 | + x -= 1 |
| 63 | + if y >= 0: |
| 64 | + if b[y] == '1': |
| 65 | + carry += 1 |
| 66 | + y -= 1 |
| 67 | + arr.append(chr((carry & 1) + ord('0'))) |
| 68 | + carry >>= 1 |
| 69 | + if carry == 1: |
| 70 | + arr.append('1') |
| 71 | + return ''.join(reversed(arr)) |
52 | 72 | ```
|
53 | 73 |
|
54 | 74 | ### **Java**
|
55 | 75 |
|
56 | 76 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
57 | 77 |
|
58 | 78 | ```java
|
| 79 | +class Solution { |
| 80 | + public String addBinary(String a, String b) { |
| 81 | + int x = a.length() - 1, y = b.length() - 1; |
| 82 | + StringBuilder builder = new StringBuilder(); |
| 83 | + int carry = 0; |
| 84 | + while (x >= 0 || y >= 0) { |
| 85 | + if (x >= 0) { |
| 86 | + if (a.charAt(x) == '1') { |
| 87 | + carry += 1; |
| 88 | + } |
| 89 | + x--; |
| 90 | + } |
| 91 | + if (y >= 0) { |
| 92 | + if (b.charAt(y) == '1') { |
| 93 | + carry += 1; |
| 94 | + } |
| 95 | + y--; |
| 96 | + } |
| 97 | + builder.append((char) ((carry & 1) + '0')); |
| 98 | + carry >>= 1; |
| 99 | + } |
| 100 | + if (carry == 1) { |
| 101 | + builder.append('1'); |
| 102 | + } |
| 103 | + return builder.reverse().toString(); |
| 104 | + } |
| 105 | +} |
| 106 | +``` |
59 | 107 |
|
| 108 | +### **Go** |
| 109 | + |
| 110 | +```go |
| 111 | +func addBinary(a string, b string) string { |
| 112 | + x, y := len(a)-1, len(b)-1 |
| 113 | + var builder strings.Builder |
| 114 | + carry := 0 |
| 115 | + for x >= 0 || y >= 0 { |
| 116 | + if x >= 0 { |
| 117 | + if a[x] == '1' { |
| 118 | + carry += 1 |
| 119 | + } |
| 120 | + x-- |
| 121 | + } |
| 122 | + if y >= 0 { |
| 123 | + if b[y] == '1' { |
| 124 | + carry += 1 |
| 125 | + } |
| 126 | + y-- |
| 127 | + } |
| 128 | + builder.WriteRune(rune(carry&1 + '0')) |
| 129 | + carry >>= 1 |
| 130 | + } |
| 131 | + if carry == 1 { |
| 132 | + builder.WriteRune('1') |
| 133 | + } |
| 134 | + bytes := []byte(builder.String()) |
| 135 | + for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 { |
| 136 | + bytes[i], bytes[j] = bytes[j], bytes[i] |
| 137 | + } |
| 138 | + return string(bytes) |
| 139 | +} |
60 | 140 | ```
|
61 | 141 |
|
62 | 142 | ### **...**
|
|
0 commit comments