简体   繁体   English

球拍二进制加法

[英]Racket Binary Addition

I have a question concerning Racket. 我有一个关于球拍的问题。 Given 2 string binary numbers, I would like to obtain their sum in a string binary number. 给定2个字符串二进制数,我想以字符串二进制数获取它们的总和。 The function should take into account carry bits and a possible overflow. 该功能应考虑进位和可能的溢出。 So the function should look like this: 因此该函数应如下所示:

(define (binary-sum a b) ...)

For example: 例如:

(binary-sum "010" "001")

"011"

Or: 要么:

(binary-sum "0010" "1011")

"1101"

Or in case of overflow: 或在发生溢出的情况下:

(binary-sum "1111" "0001")

"overflow"

Please identify any packages I need. 请确定我需要的任何包裹。

Thank you! 谢谢!

Binary values in Racket are specified using the prefix #b . 使用前缀#b指定Racket中的二进制值。 Using that, we can create the following function: 使用它,我们可以创建以下函数:

> (define (binary-sum a b)
  (+ (string->number (string-append "#b" a))
     (string->number (string-append "#b" b))))

> (binary-sum "010" "001")
3

To format the output as binary as well, we can use ~r , like so: 要将输出格式也设置为二进制,我们可以使用~r ,如下所示:

> (define (binary-sum a b)
  (~r (+ (string->number (string-append "#b" a))
      (string->number (string-append "#b" b))) #:base 2))

> (binary-sum "010" "001")
011

And finally, to add your overflow feature, we can simply compare the length of our result as a string to the length of one of the parameters. 最后,要添加您的溢出功能,我们可以简单地将结果的字符串长度与参数之一的长度进行比较。

(define (binary-sum a b)
  (let ((sum (~r (+ (string->number (string-append "#b" a))
                    (string->number (string-append "#b" b)))
                 #:base 2)))
    (if (> (string-length sum)
           (string-length a))
        "overflow"
        sum)))

Which behaves exactly as your question specifies. 它的行为与您的问题所指定的完全相同。 Let me know if you have any remaining doubts or confusion. 如果您还有其他疑问或困惑,请告诉我。 Good luck! 祝好运!

Edit: Just wanted to note that if you ever need to merely add two binary values and don't mind getting an integer back, you can always just do it like so: 编辑:只是要注意,如果您只需要添加两个二进制值并且不介意取回整数,则总是可以这样进行:

> (+ #b010 #b001)
3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM