0
Scheme에서 이진수의 특정 비트를 변경할 수있는 기능을 구현해야합니다.Scheme (Racket)에서 이진수의 특정 인덱스 비트 변경
입력은 다음과 같습니다. 1. 이진수, 2. 변경할 비트의 색인, 3. 해당 색인에 설정할 값.
어떻게 구현할 수 있습니까?
Scheme에서 이진수의 특정 비트를 변경할 수있는 기능을 구현해야합니다.Scheme (Racket)에서 이진수의 특정 인덱스 비트 변경
입력은 다음과 같습니다. 1. 이진수, 2. 변경할 비트의 색인, 3. 해당 색인에 설정할 값.
어떻게 구현할 수 있습니까?
(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)])))
여기가 해결책의 시작입니다. 나머지 사례에서 수행해야 할 작업을 확인할 수 있습니까?
; 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?>
]))
당신이 거기서 무엇을했는지 설명해 주시겠습니까? (경우에 따라 변경할 비트의 색인은 오른쪽에서 왼쪽으로 1에서 n까지 계산해야 함) – BVtp
답변이 좋을 때까지는 더 많은 정보를 제공하는 것이 좋습니다. 세부. –