0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyアルゴリズム(Add Binary)

0
Posted at

問題

Given two binary strings a and b, return their sum as a binary string.

Example 1:

Input: a = "11", b = "1"
Output: "100"
Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Constraints:

1 <= a.length, b.length <= 10^4
a and b consist only of '0' or '1' characters.
Each string does not contain leading zeros except for the zero itself.

私の回答

def add_binary(a, b)
    (a.to_i(2) + b.to_i(2)).to_s(2)
end

無事Accepted!!

どう考えたか書いていきます。
といっても今回そのままなのですが。。。

まず問題としては二進数の足し算ですが、普通にto_iして足し算してしまうと二進数と十進数が混ざった計算になってしまうので、

a = "1010"
a.to_i(2) #=> 10

十進数に変換します。
十進数として計算した後、二進数に再度変換します。

a.to_i(2) + b.to_i(2) #=> 21
21.to_s(2) #=> "10101"

無事終了です。

本当は最初、integerにした後桁ごとに計算しなければいけないのかな?と思いましたが、もっとシンプルに書けました。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?