2017-04-14 9 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?> 
    ])) 
関連する問題