Reputation: 1
This is a JavaScript program that's suppose to return the Max value of (a & b) which is also less than k ( i.e Max value of a & b < k )... But it returns a value one less than max value instead... Note: a must be less than b;
function data(n, k) {
var res = [];
for (var i = 1; i <= n; i++) {
for (var j = 2; j <= n; j++) {
if (i >= j) continue;
let a = i.toString(2);
let b = j.toString(2);
var c = a & b;
c = parseInt(c, 2);
res.push(c)
}
}
var res = res.filter(function(e) {
return e < k;
});
return Math.max(...res);
}
console.log( data(955, 236) );
It returns 234, instead of 235... I have tried other methods like Reduce and all... But i think my problem stems from where i compared the bitwise and of a & b...
Upvotes: 0
Views: 288
Reputation: 1
function data(n, k) { var res = 0;
for (var a = 1; a <= n; a++) {
for (var b = 2; b <= n; b++) {
if (i >= j) continue;
if ((a & b) < k && (a & b ) > res ) {
res = ( a & b) ;
}
}
}
return res;
}
console.log ( data ( 955, 236) ) ;
Upvotes: 0
Reputation: 23863
To be honest, I have no idea what this code is supposed to do... But I can tell you that this code does not do what you think it does.
let a = i.toString(2);
let b = j.toString(2);
var c = a & b;
toString
turns it into a string. The toString(2)
turns into a string that represents the binary value. This is different from being the actual value.
bitwise operators, like &
work on integers. The compiler will try to turn the string into a number... but it will be working in base 10 at that point and thus, you'll get a totally different number than you expected.
Most like what you mean is c = i & j
You don't have to turn the numbers into binary. Inside the computer they are already binary. The computer just turns them into base 10 when you ask it show them to you.
Upvotes: 2