Get the complement of an integer (Ruby)
Say you have a natural number and you want its binary representation first. We can achieve it in Ruby with the following line of code:
binary_of_a_number = number.to_s(2).to_i
Once we get the binary representation of a number, to get its complement, you can either XOR it with all 1s, or you could just flip the bits in a traditional way like this -
def get_integer_complement( number )
# convert into binary
binary_n = number.to_s(2)
# save into integer array by splitting
binary_array = binary_n.split("").map(&:to_i)
result_array = []
binary_array.each do |el|
el == 0 ? result_array << 1 : result_array << 0
end
return result_array.join.to_i(2)
end
Written by Goutham Harsha
Related protips
1 Response
Why not ~
?
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#