You are viewing a single comment's thread. Return to all comments →
Here are my JavaScript solutions passing all test cases:
1) using BigInt to covert strings from hex to bin and back:
function aOrB(k, a, b, c) { [a, b, c] = [a, b, c].map(hex => Array.from(BigInt('0x' + hex).toString(2))); const maxLen = Math.max(a.length, b.length, c.length); [a, b, c] = [a, b, c].map(bin => bin.length === maxLen ? bin : Array(maxLen - bin.length).fill('0').concat(bin)); const bit = ch => ch === '1'; for(let i = 0; i < maxLen; i++) { if(bit(c[i])) { if(!bit(a[i]) && !bit(b[i])) b[i] = '1', k--; } else { if(bit(a[i])) a[i] = '0', k--; if(bit(b[i])) b[i] = '0', k--; } if(k < 0) return console.log('-1'); } for(let i = 0; i < maxLen && k > 0; i++) { if(bit(a[i]) && bit(b[i])) a[i] = '0', k--; else if(bit(a[i]) && !bit(b[i]) && k > 1) { a[i] = '0', b[i] = '1', k -= 2; } } [a, b].forEach(bin => console.log(BigInt('0b' + bin.join('')).toString(16).toUpperCase())); }
2) converting hex to bin and bin to hex manually:
function aOrB(k, a, b, c) { const map = new Map(); for(let i = 0, hex = '0123456789ABCDEF'; i < 16; i++) { const bin_i = [8, 4, 2, 1].reduce((res, j) => res.concat(i & j ? '1' : '0'), ''); map.set(hex[i], bin_i).set(bin_i, hex[i]); } const maxLen = 4 * Math.max(a.length, b.length, c.length); [a, b, c] = [a, b, c].map(hex => { const bin = Array(maxLen - 4 * hex.length).fill('0'); for(let i = 0; i < hex.length; i++) { bin.push(...map.get(hex[i])); } return bin; }); const bit = ch => ch === '1'; for(let i = 0; i < maxLen; i++) { if(bit(c[i])) { if(!bit(a[i]) && !bit(b[i])) b[i] = '1', k--; } else { if(bit(a[i])) a[i] = '0', k--; if(bit(b[i])) b[i] = '0', k--; } if(k < 0) return console.log('-1'); } for(let i = 0; i < maxLen && k > 0; i++) { if(bit(a[i]) && bit(b[i])) a[i] = '0', k--; else if(bit(a[i]) && !bit(b[i]) && k > 1) { a[i] = '0', b[i] = '1', k -= 2; } } [a, b].forEach(bin => { for(var i = 4, hex = ''; i <= maxLen; i += 4) { hex += map.get(bin.slice(i - 4, i).join('')); } console.log(hex.replace(/(?<=^)0+/, '') || '0'); }); }
Seems like cookies are disabled on this browser, please enable them to open this website
A or B
You are viewing a single comment's thread. Return to all comments →
Here are my JavaScript solutions passing all test cases:
1) using BigInt to covert strings from hex to bin and back:
2) converting hex to bin and bin to hex manually: