How to calculate the sum of the digits of a number in a chart?

I want to calculate the sum of the digits of a number in a Scheme. It should work as follows:

>(sum-of-digits 123)
 6

My idea is to convert a number 123to a string "123", and then convert it to a list '(1 2 3), and then use (apply + '(1 2 3))to get 6.

but it, unfortunately, does not work, as I imagined.

>(string->list(number->string 123))
'(#\1 #\2 #\3)

Apparently '(#\1 #\2 #\3)not the same as '(1 2 3)... because I use the language racketin DrRacket, so I cannot use a type function char->digit.

Can someone help me fix this?

+3
source share
6 answers

. , , Lisp ( ):

(defun sum-of-digits(x) 
  (if (= x 0) 0 
      (+ (mod x 10) 
         (sum-of-digits (/ (- x (mod x 10)) 10)))))
+6

, #\1, #\2, . RTFM , Racket . Drracket F1, .

; , , , "" :

(map string (list #\a #\b))

...

(list "a" "b")
+1

- , :

(define (digits n)
    (if (zero? n)
        '()
        (cons (remainder n 10) (digits2 (quotient n 10))))

, idk, , , Project Euler. , .

- , :

(foldr + (digits 12345) 0)

(apply + (digits 1234))

EDIT - intLength , , .

(define (intLength x)
   (define (intLengthP x c)
      (if (zero? x)
          c
          (intLengthP (quotient x 10) (+ c 1))
      )
   )
   (intLengthP x 0))
+1
source

It would be best to find the numbers and summarize them. 34%10gives 4and 3%10gives 3. Amount 3+4.

Here is the algorithm in F # (sorry, I don't know Schemas):

let rec sumOfDigits n =
    if n<10 then n
    else (n%10) + sumOfDigits (n/10)
0
source

This works, it is based on your original solution string-> list, just does the conversion to a list of characters

(apply + (map (lambda (d) (- (char->integer d) (char->integer #\0)))
       (string->list (number->string 123))))

The conversion function can be modified to make it more understandable:

(define (digit->integer d)
  (- (char->integer d) (char->integer #\0)))

(apply + (map digit->integer (string->list (number->string 123))))
0
source
(define (sum-of-digits num)
    (if (< num 10)
        num
        (+ (remainder num 10) (sum-of-digits (/ (- num (remainder num 10)) 10)))))
Recursive process

ends at n < 10, where sum-of-digitsthe input itself returns num.

-1
source

All Articles