The biggest problem is that you’re not taking the characters in the correct order, you’re taking the first one and doing the exponent with the smallest magnitude when the first character is the greatest, so you have to reverse the exponent calculation or take the characters backwards, which is what I chose. There’s still a way to sweep the loop backwards from the end to the beginning, but I don’t think it’s worth it, I’d still have two cases backwards and I’d need a calculation to do.
It’s not a mistake, but you don’t need if
, enough math, if the values can only be 0 or 1 multiplied by 0 always gives 0 and multiplying by 1 always gives the value itself.
Just one last comment: what you’re doing is a parse of a text that has a pattern that is presumed to be a binary notation of a number and wants to convert to number, point, not number. Number is number, notation is notation, so there is a decimal notation, but there is no decimal number.
The simple, efficient way (does not make memory and processing allocations to manipulate the string) and pure mathematics would be like this (if it’s an exercise you can’t use library resources I think it would be like this):
let bin = '1110';
let dec = 0;
for (let c = 0; c < bin.length; c++) dec += Math.pow(2, c) * bin[bin.length - c - 1]; //calcula para pegar do último ao primeiro
console.log(dec);
I put in the Github for future reference.
It wasn’t easier to start the loop with the
bin.length - 1
and decreasec
to zero? No need to invert the string...– hkotsubo
@hkotsubo, I thought about doing this, but I couldn’t use the power index without doing the calculation Maniero did on his answer. It would end up giving a problem similar to the question. See here.
– Luiz Felipe
Just create another pro exponent variable :-) I think it’s better to invert the string (even more than Javascript doesn’t have a native method and makes us have to create an array...)
– hkotsubo
Thank you Luizfelipe and @Maniero I will do some tests implementing your solutions, I’m beginner so I’m picking up with some things yet. Thanks for the explanations.
– Caroline Santos