This code is meant to convert a binary string ("100101") to its decimal equivalent. I am struggling to identify the issue causing it to not work properly. Any assistance would be greatly appreciated.
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
for(var j=0;j<num.length;i++){
sum+=Math.pow(2,i)*num[j];
}
}
return sum;
};
Below is my revised code. For an input of "011", it is intended to compute (2^2*0 +2^1*1 +2^0*1) which should be 3, but currently, it outputs 14. Can anyone pinpoint where I've made a mistake?
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
for(var j=0;j<num.length;j++){
sum+=Math.pow(2,i)*num[j];
}
}
return sum;
};