R
E
A
C
T
O
xamples
epeat
ode
pproach
ptimize
est
{ Bit Shifting }
The Question
A bit shift moves each digit in a set of bits left or right. The last bit in the direction of the shift is lost, and a bit is inserted on the other end.
0010 << // 0100
1011 >> // 0101
1010110 << 2 // 1011000
1011010 >> 3 // 0001011
Bit shifts can optionally take a number of times to shift
Note that each shift to the left multiplies a number by 2 to that power, and each shift to the right divides a number by two to that power (ex. a left shift of 3 multiplies the number by 8)
What you need to do:
Write a function with the following signature:
function (binaryString, direction, numShifts) {}
- binaryString will be a string representing a binary number (ex. "1010"). It will always contain a valid string with 0s and 1s
- direction will be a string - either "left" or "right"
- numShifts will be a number representing the number of times to shift. If left empty, the shift should be 1. It will either contain a valid whole number greater than 0 or be null
Approach
- Your first instinct is probably to start looping...
- You can simply slice and dice the string - run through several examples and you'll see the pattern
- Did you know that ES6 introduces a handy new repeat function on String.prototype...?
Possible Solution
function bitShift (binString, direction, numShifts) {
numShifts = numShifts || 1;
let l = binString.length,
zeroes = "0".repeat(numShifts);
if (direction === 'left') return binString.slice(numShifts, l).concat(zeroes);
else return zeroes.concat(binString.slice(0, l - numShifts));
}
Conclusion
REPL.IT solutions
- Looking for patterns in your expected output can lead to simple, elegant solutions
- String.prototype.repeat is quite handy! Check out some more new String.prototype methods:
startsWith, endsWith, includes
Bit Shifting
By Tom Kelly
Bit Shifting
Technical interview problem to implement a bit shifting algorithm
- 1,326