Transform a natural number to a specific base and return it as a list

此生再无相见时 提交于 2019-12-02 09:07:56

I think you have to rethink this problem. Appending results to a global variable is definitely not the way to go, let's try a different approach via tail recursion:

(define (num->base n b)
  (let loop ((n n) (acc '()))
    (if (< n b)
        (cons n acc)
        (loop (quotient n b)
              (cons (modulo n b) acc)))))

It works as expected:

(num->base 12345 10)
=> '(1 2 3 4 5)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!