DEV Community

Discussion on: Daily Challenge #24 - Shortest Step

Collapse
 
willsmart profile image
willsmart • Edited

JS using a bit of bitwise math


// Wow,.. fancy :|
step = n => (n&~1) >> ((~n)&1)    // note that they're ~'s, not -'s

// Count how many times we need to iterate step until it hits 0
countSteps = n => {
  if (n<=0 || Math.floor(n)!==n) throw new Error(`countSteps only accepts positive integers, ${n} was passed`);

  let count =0;
  while (n=step(n)) count++;
  return count;
}

(couple of edits to make it cleaner)