2017-04-14 30 views

回答

0
(define (set-bit value index n) 
    (let ([mask (arithmetic-shift 1 index)]) 
    (cond [(= value 0) (bitwise-and (bitwise-not mask) n)] 
      [(= value 1) (bitwise-ior mask n)]))) 
+0

你能解釋一下你在那裏做了什麼嗎? (此外,爲了以防萬一,要改變的位的索引必須從右到左,從1到n ...)計算 – BVtp

+0

只要答案可能是好的,那麼給予更多一點是有意義的細節。 –

1

這是一個解決方案的開始。你能否看到剩下的情況需要做些什麼?

; bit-index->number : natural -> natural 
; return the number which in binary notation has a 1 in position n 
; and has zeros elsewhere 
(define (bit-index->number n) 
    (expt 2 n)) 

; Example 
(displayln (number->string (bit-index->number 3) 2)) 
; 1000 

; is-bit-set? : index natural -> boolean 
; is bit n set in the number x? 
(define (is-bit-set? n x) 
    ; the bitwise-and is zero unless bit n is set in the number x 
    (not (zero? (bitwise-and (bit-index->number n) x)))) 

(define (set-bit! n x b) 
    (cond 
    [(= b 1) ; we need to set bit n in x to 1 
    (cond 
     [(is-bit-set? n x) x]        ; it was already set 
     [else    (+ x (bit-index->number n))])] ; add 2^n 
    [(= b 0) 
    ; <what goes here?> 
    ]))