5 kyu

Common Bit Twiddles

278 of 428user5854572

Description:

In this kata, we are throwing readablity to the wind and are refactoring simple functions to use Bit Twiddling.

Specifications

The functions we will make are:

  • isEven
  • isOdd
  • halfAndFloor
  • isPowerOfTwo
  • nthPowerOfTwo
  • truncate (note: not in Haskell)
  • abs

You are only allowed to use bitwise / boolean operators (and corresponding assignment operators): !, &&, ||, &, |, ^, ~, <<, >>, >>>, +, and -.

You should not use ?, :, *, /, %, if, else, for, while, do, switch, case, or the object Math.

###Code Examples

//All inputs are between + or - 2147483647

//Only receives whole numbers
isEven(2) // true
isEven(1) // false

//Only receives whole numbers
isOdd(2) // false
isOdd(1) // true

//Only receives positive whole numbers
halfAndFloor(10) // 5
halfAndFloor(11) // 5

//Only receives positive whole numbers
isPowerOfTwo(256) // true
nthPowerOfTwo(4) // 16

//Receives decimal numbers
truncate(1.1) // 1

//Receives negative / positive whole numbers
abs(-1) // 1
isEven 2 // True
isEven 1 // False

isOdd 2 // False
isOdd 1 // True

halfAndFloor 10 // 5
halfAndFloor 11 // 5

isPowerOfTwo  256 // True

nthPowerOfTwo   4 // 16

abs (-1) --> 1
Binary
Bits
Refactoring

Stats:

CreatedSep 24, 2014
PublishedSep 25, 2014
Warriors Trained1023
Total Skips216
Total Code Submissions2943
Total Times Completed428
JavaScript Completions278
Haskell Completions156
Total Stars40
% of votes with a positive feedback rating94% of 86
Total "Very Satisfied" Votes77
Total "Somewhat Satisfied" Votes7
Total "Not Satisfied" Votes2
Ad
Contributors
  • user5854572 Avatar
  • jhoffner Avatar
  • bkaes Avatar
  • solitude Avatar
  • utoppia Avatar
Ad