如何计算数字的个数?

编程入门 行业动态 更新时间:2024-10-10 09:19:07
本文介绍了如何计算数字的个数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

  • (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.0

    Indicating that 10000! produces an answer consisting of 35660 digits.

    更多推荐

    如何计算数字的个数?

    本文发布于:2023-11-29 10:06:21,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1646096.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:个数   数字

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!