如何计算数字的个数? [英] How to count number of digits?

查看:83
本文介绍了如何计算数字的个数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

  1. (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 位数字组成的答案.

  1. (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.

这篇关于如何计算数字的个数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆