问题
This is the code I want translated into Racket:
public static ArrayList<Integer> convert(int k, int n) {
ArrayList<Integer> lst = new ArrayList<>();
while (k / n != 0) {
lst.add(k % n);
k = k/n;
}
lst.add(k % n);
return lst;
}
e.g. in Racket the (convert 23 2)
should return the binary of the decimal 23, which is (list 1 0 1 1 1)
.
This is what I got so far:
(define (convert k n)
(cond
[(> (/ k n) 0) (list(modulo k n))]
[else 0]
))
It works for the first element of the list.
Thanks for any help!
回答1:
Be aware that the /
operator in Java performs integer division, so in Racket you'd have to use quotient
to obtain the same effect.
This is a good opportunity to use a named let
to implement the loop, as the result list needs to be accumulated in reverse. Other than that, the solution is pretty straightforward:
(define (convert k n)
(let loop ((k k) (acc '()))
(if (zero? (quotient k n))
(cons (modulo k n) acc)
(loop (quotient k n) (cons (modulo k n) acc)))))
For example:
(convert 23 2)
=> '(1 0 1 1 1)
来源:https://stackoverflow.com/questions/59993838/how-can-i-transform-this-code-into-racket-scheme