我正在尋找有關計劃問題的幫助。在計劃中提取數字
我試圖在產生向後相對與n的數字的方式來提取在方案號
(提取 - 數NK)
例如,(提取 - 數4321 0)應產生1和(extract-number 4321 1)應該產生2. 而且,n可以是任意長度,並且k可以被假定爲小於長度
我正在尋找有關計劃問題的幫助。在計劃中提取數字
我試圖在產生向後相對與n的數字的方式來提取在方案號
(提取 - 數NK)
例如,(提取 - 數4321 0)應產生1和(extract-number 4321 1)應該產生2. 而且,n可以是任意長度,並且k可以被假定爲小於長度
假設輸入數字是基於非負值10並且該指數是有效的,訣竅是通過連續商數「遍歷」該數字,直到找到t爲止他預計指數或者數字不足。試試這個:
(define (extract-number n k)
(cond ((zero? k) (modulo n 10))
((<= n 0) (error "Invalid input"))
(else (extract-number (quotient n 10) (sub1 k)))))
例如:
(extract-number 4321 0)
=> 1
(extract-number 4321 1)
=> 2
(extract-number 10 3)
=> Invalid input
這是一種通過使用POS機參數更改號碼爲字符串,使一個子做:
(define (extractNum num pos)
(string->number (substring (number->string num)
(- (string-length (number->string num)) (+ 1 pos))
(- (string-length (number->string num)) pos))))
; last-digit : number -> digit
; return the last digit of n
; Example: (last-digit 123) is 3
(define (last-digit n)
(remainder n 10))
; remove-last-digit : number -> number
; Example: (remove-last-digit 123) is 12
(define (remove-last-digit n)
(quotient n 10))
; digits : number -> list-of-digits
; return the digits of n
; Example: (digits 123) is (list 3 2 1)
(define (digits n)
(if (<= 0 n 9)
(list n)
(cons (last-digit n)
(digits (remove-last-digit n)))))
(define (extract-number n k)
(list-ref (digits n) k))
另一種定義number->digits
的方法:
(define (number->digits n)
(reverse (string->list (number->string n))))