DEV Community

Discussion on: Daily Challenge #24 - Shortest Step

Collapse
 
wheatup profile image
Hao • Edited

If you convert the number to binary, the steps are exactly

(number of 1s - 1) * 2 + number of 0s

2  -> "10"   -> (1 - 1) * 2 + 1 = 1 step
7  -> "111"  -> (3 - 1) * 2 + 0 = 4 steps
12 -> "1100" -> (2 - 1) * 2 + 2 = 4 steps

This way we don’t need loops or recursion.

String.prototype.count = function(char){
  return this.split(char).length - 1;
}

function countSteps(n) {
  let binary = n.toString(2);
  return (binary.count('1') - 1) * 2 + binary.count('0');
}
Collapse
 
coreyja profile image
Corey Alexander

Wow this is brilliant! Nice job!

Collapse
 
maxart2501 profile image
Massimo Artizzu

I was about to submit something like that, so have my applause instead πŸ‘πŸŽ‰

A little more thinking on the problem can really simplify the solution!

(On a side note, I wouldn't extend a native prototype, but that's out of context now πŸ˜…)

Collapse
 
wheatup profile image
Hao

That was my original version, then I thought writing two functions might confuse people so I changed it into this. It's just for the sake of demonstration and better readability.πŸ€—But you were right, it is a bad habit to extend a native prototype.