Last Updated: February 25, 2016
·
1.565K
· gouthamkgh

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

1 Response
Add your response

Why not ~?

over 1 year ago ·