Skip to content

Instantly share code, notes, and snippets.

@srt32
Last active January 4, 2016 20:29
Show Gist options
  • Save srt32/8673881 to your computer and use it in GitHub Desktop.
Save srt32/8673881 to your computer and use it in GitHub Desktop.
writing code in a notepad :(
"1001" + "11" ---> "1100"
"1" + "1" ---> "10"
def add(number_one, number_two)
# "1011"
# "1111"
# 1110"
ones_digit = number_one[-1]
result = ""
largest_number = [number_one,number_two].max_by {|num| num.length }
smallest_number = [number_one,number_two].min_by {|num| num.length }
largest_index = largest_number.size - 1
smallest_index = smallest_number.size - 1
carry = 0
loop
larger_digit = largest_number[largest_index]
smaller_digit = smaller_number[smallest_index]
sum = one_digit.to_i + two_digit.to_i + carry # -> 1
carry = 0
# deal with the carry
if sum <= 1
result = sum + result
elsif sum == 2
result = "0" + result
carry = 1
elsif sum == 3
result = "1" + result
carry = 1
end
# decrement the index
index -= 1 # update indices
# add the carry if carry != 0 && index == -1
break if index == -1
end
result = "1" + result if carry > 0
result
end
[-1, 10, 8, 2, 5, -3, 4, 9, 0], 9
[-3, -1, 0, 2, 4, 5, 8, 9, 10]
10 + -3 = 7
10 + -1 = 9
9 + 0 = 9 # -> [2, 4, 5, 8]
[2, 4, 5, 8, 9, 10]
10 + 2 = 12
bump the right
def pairs(array, goal)
# sort
array = array.sort
result = []
right_index = arary.length - 1
left_index = 0
loop
right_digit = array[right_index]
left_digit = array[left_index]
sum = right_digit + left_digit
if sum == goal
puts right_digit + left_digit
left_index += 1
right_index -= 1
elsif sum < goal
left_index += 1
else # > goal
right_index -= 1
end
break if right_index == left_index
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment