如何在Common Lisp中将十进制数字转换为八进制数字列表? [英] How do I convert a decimal number to a list of octal digits in Common Lisp?
本文介绍了如何在Common Lisp中将十进制数字转换为八进制数字列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要按正确的顺序排列结果。它仅适用于小于100的数字。
I need to have the result in correct order. It works for numbers less than 100 only.
(base8 8)
给出(1 0)
,
(base8 20)
给出( 2 4)
,
,但
(base8 100)
给出(414)
而不是(144)
。
I尝试了2天,找不到问题。请帮我。
I tried for 2 days and can not find the problem. Please help me.
(defun base8(n)
(cond
((zerop (truncate n 8)) (cons n nil))
(t (reverse (cons (mod n 8)
(base8 (truncate n 8)))))))
推荐答案
问题是您将字符串反转了几次。将执行以下操作:
The problem is that you are reversing the string a few times. The following will do:
(defun base8 (n)
(let ((t8 (truncate n 8)) (m8 (mod n 8)))
(if (= t8 0)
(list m8)
(append (base8 t8) (list m8)))))
编辑
这里是不带追加
的解决方案,使用辅助函数。您会清楚地看到,一个 反向就足够了:
Here's a solution without append
, using a helper function. You'll see clearly that one reverse is enough:
(defun base8-helper (n)
(let ((t8 (truncate n 8)) (m8 (mod n 8)))
(cons m8 (if (= t8 0)
nil
(base8-helper t8)))))
(defun base8 (n)
(reverse (base8-helper n)))
或带有累加器(尾递归)
or, with an accumulator (tail-recursive)
(defun base8 (n &optional (acc '()))
(let ((t8 (truncate n 8)) (m8 (mod n 8)))
(if (= t8 0)
(cons m8 acc)
(base8 t8 (cons m8 acc)))))
这篇关于如何在Common Lisp中将十进制数字转换为八进制数字列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文