Skip to content

Instantly share code, notes, and snippets.

@saolsen
Created August 26, 2014 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saolsen/699bff0085ba4a6ac5b4 to your computer and use it in GitHub Desktop.
Save saolsen/699bff0085ba4a6ac5b4 to your computer and use it in GitHub Desktop.
number to binary
#lang racket
(define (get-spaces-inner n spaces)
(define current-space (car spaces))
(if (> current-space n)
(cdr spaces)
(get-spaces-inner n (cons (* current-space 2) spaces))))
(define (get-spaces n)
(get-spaces-inner n '(1)))
(define (to-binary x spaces)
(define binary-digits
(first
(foldl (lambda (place val)
(define digits (first val))
(define n (second val))
(if (>= n place)
(list (cons 1 digits) (- n place))
(list (cons 0 digits) n)))
(list '() x)
spaces)))
(reverse binary-digits))
(define (number-to-binary n)
(define spaces (get-spaces n))
(to-binary n spaces))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment