Logo

Programming-Idioms

History of Idiom 76 > diff from v82 to v83

Edit summary for version 83 by cousinitt:
New Scheme implementation by user [cousinitt]

Version 82

2020-12-29, 10:51:33

Version 83

2021-07-14, 03:32:10

Idiom #76 Binary digits from an integer

Create the string s of integer x written in base 2.

E.g. 13 -> "1101"

Idiom #76 Binary digits from an integer

Create the string s of integer x written in base 2.

E.g. 13 -> "1101"

Variables
s,x
Variables
s,x
Extra Keywords
int radix print
Extra Keywords
int radix print
Code
(define (binary-representation x)
  (let loop ([N x]
             [s '()])
    (let ([NN (arithmetic-shift N -1)])
      (cond [(zero? N) (list->string s)]
            [(odd? N) (loop NN (cons #\1 s))]
            [else (loop NN (cons #\0 s))]))))