64 lines
1.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @param {string} a
* @param {string} b
* @return {string}
*/
const addBinary = function (a, b) {
};
/*
直接利用位运算,只算进位加法,和只算不进位加法,得到得结果求和就是要求得结果,投机
取巧使用数字快速运算被大数卡住了f1只作为思路扩张
*/
function f1(a, b) {
// 将二进制字符串转换为十进制整数
let x = parseInt(a, 2);
let y = parseInt(b, 2);
// 使用位运算求和
while (y !== 0) {
const sum = x ^ y; // 不带进位的加法
const carry = (x & y) << 1; // 进位
x = sum;
y = carry;
}
// 把结果转换成二进制字符串
return x.toString(2);
}
/*
模拟加法操作从个位开始加由于各位没有人给我进位所以初始进位carry位0每一位相加再加上它得进位
计算本位和进位知道没有进位和ab所有位处理完毕
*/
function f2(a, b) {
let i = a.length - 1; // 指针 i 指向 a 的最后一位(最低位)
let j = b.length - 1; // 指针 j 指向 b 的最后一位(最低位)
let carry = 0; // 初始化进位为 0
const res = []; // 用于存储结果的数组(从低位到高位)
// 循环条件:只要还有位未处理,或还有进位,就继续
while (i >= 0 || j >= 0 || carry !== 0) {
// 取当前位的值,如果越界则视为 0
const bitA = i >= 0 ? +a[i] : 0;
const bitB = j >= 0 ? +b[j] : 0;
// 本位加法:两个二进制位 + 上一轮进位
const sum = bitA + bitB + carry;
// sum % 2 得到当前位的结果(因为二进制满 2 进 1
res.push(sum % 2);
// 计算下一轮的进位(如果 sum >= 2 则进位为 1
carry = Math.floor(sum / 2);
// 移动指针,处理更高位
i--;
j--;
}
// 最后结果数组是反着存的,需要翻转后拼接成字符串
return res.reverse().join('');
}