2021-05-01 17:38:17 -04:00
|
|
|
def binary_xor(x, y)
|
2021-09-03 13:24:58 -07:00
|
|
|
raise 'Input must only contain positive integers' if (x < 0) || (y < 0)
|
2021-05-01 17:38:17 -04:00
|
|
|
|
|
|
|
binary_x = x.to_s(2)
|
|
|
|
binary_y = y.to_s(2)
|
|
|
|
|
|
|
|
if binary_x.length > binary_y.length
|
2021-09-03 13:24:58 -07:00
|
|
|
prefix = '0' * (binary_x.length - binary_y.length)
|
2021-05-01 17:38:17 -04:00
|
|
|
binary_y = prefix + binary_y
|
|
|
|
elsif binary_y.length > binary_x.length
|
2021-09-03 13:24:58 -07:00
|
|
|
prefix = '0' * (binary_y.length - binary_x.length)
|
2021-05-01 17:38:17 -04:00
|
|
|
binary_x = prefix + binary_x
|
|
|
|
end
|
2021-09-03 13:24:58 -07:00
|
|
|
result = '0b'
|
2021-05-01 17:38:17 -04:00
|
|
|
binary_x.each_char.with_index do |x_char, i|
|
|
|
|
y_char = binary_y[i]
|
|
|
|
|
2021-09-03 13:24:58 -07:00
|
|
|
result += if (x_char == '1' && y_char != '1') || (x_char != '1' && y_char == '1')
|
|
|
|
'1'
|
|
|
|
else
|
|
|
|
'0'
|
|
|
|
end
|
2021-05-01 17:38:17 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
result
|
|
|
|
end
|
|
|
|
|
|
|
|
begin
|
|
|
|
binary_xor(-1, 0)
|
2021-09-03 13:24:58 -07:00
|
|
|
rescue StandardError => e
|
2021-05-01 17:38:17 -04:00
|
|
|
puts e.message
|
|
|
|
end
|
2021-05-02 11:49:20 -04:00
|
|
|
# Input must only contain positive integers
|
2021-05-01 17:38:17 -04:00
|
|
|
|
|
|
|
puts binary_xor(1, 1)
|
|
|
|
# 0b0
|
|
|
|
puts binary_xor(0, 1)
|
|
|
|
# 0b1
|
|
|
|
puts binary_xor(1024, 1024)
|
|
|
|
# 0b00000000000
|
|
|
|
puts binary_xor(0, 1023)
|
|
|
|
# 0b1111111111
|
|
|
|
puts binary_xor(16, 58)
|
|
|
|
# 0b101010
|