CLEAN CODE | ADD BINARY STRINGS | PATTERNS

By: Saurav

2018-02-10 07:59:00 UTC

Given two binary strings, return their sum (also a binary string).

Example:

a = "100"

b = "11"
Return a + b = “111”.

InterviewBit

This is an interesting problem just like adding two numbers. The only difference is here we use %2 instead of %10:

Let's write some tests and get on to coding:

p add_binary("1010110111001101101000", "1000011011000000111100110") == "1001110001111010101001110"
p add_binary("11", "1") == "100"
p add_binary("10", "1") == "11"

def add_binary(a,b)
  return if a.length < 1 or b.length < 1
  
  if a.length > b.length 
    b = add_lead_zero(b,a)
  elsif a.length < b.length 
    a = add_lead_zero(a,b)
  end
  
 
  carry = 0 
  total = ""
  
  (a.length-1).downto(0).each do |i|
    total += ((a[i].to_i + b[i].to_i + carry)%2).to_s
    carry = (a[i].to_i + b[i].to_i + carry)/2
  end 
  
  total += carry.to_s if carry > 0 
  
  return total.reverse
  
end


def add_lead_zero(small,bigger)
  diff = bigger.length - small.length
  diff.times do |i|
    small.prepend("0")
  end
  
  return small
end 

Look how interesting it is if we change the %2 to %10.
Now we can add any two decimal numbers in string format. That means both this question and Add 1 to a number have the same idea which applies to any problem with the addition of two number representing strings.

All our tests pass. All our functions do one and only one thing.

And so we are done for now :)


Let me know what you think!
twitter: sprakash24oct
linkedin

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)