(CountDigits n) 接受一个正整数 n,并返回它包含的位数.例如,
(CountDigits 1) → 1(CountDigits 10) → 2(CountDigits 100) → 3(CountDigits 1000) → 4(CountDigits 65536) → 5我想我应该使用数字的剩余部分和其他东西,但除此之外我真的迷路了.我首先尝试的是将数字除以 10,然后查看数字是否小于 1.如果是,则它有 1 位数字.如果不是,则除以 100,依此类推.但我不确定如何将其扩展到任何数字,所以我放弃了这个想法
(define (num-digits number digit)(如果(= 数字数字 0)1
解决方案偶然发现了这个,不得不提供基于日志的答案:
(定义(长度n)(+ 1 (地板 (/(log n) (log 10)))))为清楚起见进行这是一个不使用递归的 O(1) 解决方案.例如,给定
(定义(事实 n)(条件[(= n 1) 1][else (* n (事实 (- n 1)))]))(定义(长度 n)(+ 1 (地板 (/(log n) (log 10)))))运行(时间(长度(事实 10000)))产生
cpu time: 78 real time: 79 gc time: 4735660.0表示10000!产生一个由 35660 位数字组成的答案.
(CountDigits n) takes a positive integer n, and returns the number of digits it contains. e.g.,
(CountDigits 1) → 1 (CountDigits 10) → 2 (CountDigits 100) → 3 (CountDigits 1000) → 4 (CountDigits 65536) → 5
I think I'm supposed to use the remainder of the number and something else but other then that im really lost. what i tried first was dividing the number by 10 then seeing if the number was less then 1. if it was then it has 1 digit. if it doesnt then divide by 100 and so on and so forth. but im not really sure how to extend that to any number so i scrapped that idea
(define (num-digits number digit) (if (= number digit 0) 1
解决方案Stumbled across this and had to provide the log-based answer:
(define (length n) (+ 1 (floor (/ (log n) (log 10)))) )Edit for clarity: This is an O(1) solution that doesn't use recursion. For example, given
(define (fact n) (cond [(= n 1) 1] [else (* n (fact (- n 1)))] ) ) (define (length n) (+ 1 (floor (/ (log n) (log 10)))) )Running (time (length (fact 10000))) produces
cpu time: 78 real time: 79 gc time: 47 35660.0Indicating that 10000! produces an answer consisting of 35660 digits.
更多推荐
如何计算数字的个数?
发布评论