如果字符串太大,如何按位或两个二进制字符串仅包含 0 和 1? 说字符串长度最多 500

问题描述

如果字符串太大,如何按位或两个二进制字符串(仅包含 0 和 1)? (比如字符串长度高达 500)

示例:

字符串1: “1111001000111001101101111100110100110011111000111111011010111111011111111010110011001111001100011101011110011111111110101100010100100001111101010110110110111110100111111001011100011111111000000101011111110110101111111101000111100010111111011111110101010110111010101010110111110110011010010011011101111”

字符串 2: “111010111111111111111110110110011111111101011100011100010011101100111100110001010110111111110100101001111101110111111010111100010111110111101111000111100101011111111001100111111010111111111011111111101010101001000010111111000110010100101101111011111010111000111111010011111100011100101111001111011111”

另外,如何将结果二进制字符串解析为整数? (基数 10)

解决方法

使用 BigInt(注意二进制字符串开头的 0b):

var String1 = "0b1111001000111001101101111100110100110011111000111111011010111111011111111010110011001111001100011101011110011111111110101100010100100001111101010110110110111110100111111001011100011111111000000101011111110110101111111101000111100010111111011111110101010110111010101010110111110110011010010011011101111";

var String2 = "0b111010111111111111111110110110011111111101011100011100010011101100111100110001010110111111110100101001111101110111111010111100010111110111101111000111100101011111111001100111111010111111111011111111101010101001000010111111000110010100101101111011111010111000111111010011111100011100101111001111011111";

var bitwise_or = BigInt(String1) | BigInt(String2);

document.querySelector('#bigint').innerText = bitwise_or; // BigInt (Base 10)
document.querySelector('#binstr').innerText = bitwise_or.toString(2); // Binary String
p { word-wrap: break-word; }
<p id="bigint"></p>
<p id="binstr"></p>

,

您可以使用索引的偏移量迭代字符串。

function or(a,b) {
    let result = '',i = Math.min(a.length,b.length),offsetA = a.length - i,offsetB = b.length - i;
    
    while (i--) result = (a[i + offsetA] | b[i + offsetB]) + result;
    result = a.slice(0,offsetA) + b.slice(0,offsetB) + result;
    return result;
}

console.log(or('11','1100'));
console.log(or('1100','11'));