Leetcode67-二进制求和
给你两个二进制字符串,返回它们的和(用二进制表示)。输入为非空字符串且只包含数字 1
和 0
。
示例 1: 输入: a = "11", b = "1" 输出: "100"
示例 2: 输入: a = "1010", b = "1011" 输出: "10101"
本题的要点在于注意进位以及未处理完的那个字符串。
1 // Leetcode 67 2 // Math, string 3 var addBinary = function(a, b) { 4 if (a.length == 0 && b.length == 0) { 5 return ""; 6 } 7 8 if (a.length == 0 && b.length != 0) { 9 return b; 10 } 11 12 if (a.length != 0 && b.length == 0) { 13 return a; 14 } 15 16 PointerA = a.length - 1; PointerB = b.length - 1; carry = 0; res = ""; 17 while (PointerA >= 0 && PointerB >= 0) { 18 tempSum = parseInt(a[PointerA]) + parseInt(b[PointerB]) + carry; 19 if (tempSum >= 2) { 20 carry = 1; 21 res += (tempSum % 2).toString(); 22 } else { 23 carry = 0; 24 res += (tempSum % 2).toString(); 25 } 26 27 PointerA--; 28 PointerB--; 29 } 30
//如果A没有处理完,则继续处理A 31 if (PointerA >= 0) { 32 if (carry == 0) { 33 for (let i = PointerA; i >= 0; i--) { 34 res += a[i]; 35 } 36 } else { 37 carry = 1; 38 for (let i = PointerA; i >= 0; i--) { 39 tempSum = parseInt(a[i]) + carry; 40 if (tempSum >= 2) { 41 carry = 1; 42 res += (tempSum % 2).toString(); 43 } else { 44 carry = 0; 45 res += (tempSum % 2).toString(); 46 } 47 } 48 } 49 }
50 //如果B没有处理完,则继续处理B 51 if (PointerB >= 0) { 52 if (carry == 0) { 53 for (let i = PointerB; i >= 0; i--) { 54 res += b[i]; 55 } 56 } else { 57 carry = 1; 58 for (let i = PointerB; i >= 0; i--) { 59 tempSum = parseInt(b[i]) + carry; 60 if (tempSum >= 2) { 61 carry = 1; 62 res += (tempSum % 2).toString(); 63 } else { 64 carry = 0; 65 res += (tempSum % 2).toString(); 66 } 67 } 68 } 69 } 70 71 if (carry == 1) { 72 res += "1"; //注意最后的进位 73 } 74 75 return res.split("").reverse().join(""); 76 };