[LeetCode] 67. Add Binary 二进制数相加
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
解法: 从最低位加到最高位,当前位相加结果是%2,进位是/2,记得处理每一次的进位和最后一次的进位,最后反向输出字符。
Java:
public class Solution { public String addBinary(String a, String b) { StringBuilder sb = new StringBuilder(); int i = a.length() - 1, j = b.length() -1, carry = 0; while (i >= 0 || j >= 0) { int sum = carry; if (j >= 0) sum += b.charAt(j--) - '0'; if (i >= 0) sum += a.charAt(i--) - '0'; sb.append(sum % 2); carry = sum / 2; } if (carry != 0) sb.append(carry); return sb.reverse().toString(); } }
Java:
public class AddBinary { public String addBinary(String a, String b) { StringBuilder result = new StringBuilder(); int pointerA = a.length()-1; int pointerB = b.length()-1; int carry = 0; while(pointerA>=0 || pointerB>=0){ int sum = carry; if(pointerA>=0){ sum += (a.charAt(pointerA)-'0'); pointerA--; } if(pointerB>=0){ sum += (b.charAt(pointerB)-'0'); pointerB--; } result.append(sum%2); carry = sum/2; } if(carry!=0){ result.append('1'); } return result.reverse().toString(); } }
Python:
class Solution: # @param a, a string # @param b, a string # @return a string def addBinary(self, a, b): result, carry, val = "", 0, 0 for i in xrange(max(len(a), len(b))): val = carry if i < len(a): val += int(a[-(i + 1)]) if i < len(b): val += int(b[-(i + 1)]) carry, val = val / 2, val % 2 result += str(val) if carry: result += str(carry) return result[::-1]
Python:
class Solution: def addBinary(self, a, b): if len(a)==0: return b if len(b)==0: return a if a[-1] == '1' and b[-1] == '1': return self.addBinary(self.addBinary(a[0:-1],b[0:-1]),'1')+'0' if a[-1] == '0' and b[-1] == '0': return self.addBinary(a[0:-1],b[0:-1])+'0' else: return self.addBinary(a[0:-1],b[0:-1])+'1'
Python:
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ res = '' carry = 0 i, j = len(a) - 1, len(b) - 1 while i >= 0 or j >= 0: su = carry if i >= 0: su += int(a[i]) if j >= 0: su += int(b[j]) carry = su / 2 res += str(su % 2) i -= 1 j -= 1 if carry > 0: res += str(carry) return res[::-1]
C++ 1:
class Solution { public: string addBinary(string a, string b) { string res; size_t res_len = max(a.length(), b.length()) ; size_t carry = 0; for (int i = 0; i < res_len; ++i) { const size_t a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0; const size_t b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0; size_t sum = carry + a_bit_i + b_bit_i; carry = sum / 2; sum %= 2; res.push_back('0' + sum); } if (carry) { res.push_back('0' + carry); } reverse(res.begin(), res.end()); return res; } };
C++ 2:
class Solution { public: string addBinary(string a, string b) { string res = ""; int m = a.size() - 1, n = b.size() - 1, carry = 0; while (m >= 0 || n >= 0) { int p = m >= 0 ? a[m--] - '0' : 0; int q = n >= 0 ? b[n--] - '0' : 0; int sum = p + q + carry; res = to_string(sum % 2) + res; carry = sum / 2; } return carry == 1 ? "1" + res : res; } };
Followup:
如果不是二进制相加,而是十六进制相加呢?只要把算法中的除2和余2换成16,并添加相应的十六进制字母就行了。
如果是带小数的?
All LeetCode Questions List 题目汇总