We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
JAVASCRIPT Solution:
In case any optimization can be made, do let me know :
function andProduct(a, b) {
let A = a.toString(2);
let B = b.toString(2);
if (A.length !== B.length) return 0;
else {
let result = '';
let swap = false;
for (let i = 0; i < A.length; i++){
if (A[i] !== B[i]) {
swap = true;
result += '0';
} if(A[i] == '1' && B[i] == '1') {
if (swap == false) result += '1';
else result += '0';
} else if (A[i] == '0' && B[i] == '0') {
result += '0';
}
} return parseInt(result, 2);
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
AND Product
You are viewing a single comment's thread. Return to all comments →
JAVASCRIPT Solution: In case any optimization can be made, do let me know :
function andProduct(a, b) { let A = a.toString(2); let B = b.toString(2); if (A.length !== B.length) return 0; else { let result = ''; let swap = false; for (let i = 0; i < A.length; i++){ if (A[i] !== B[i]) { swap = true; result += '0'; } if(A[i] == '1' && B[i] == '1') { if (swap == false) result += '1'; else result += '0'; } else if (A[i] == '0' && B[i] == '0') { result += '0'; } } return parseInt(result, 2); } }