Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Conversion of binary value to an integer

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.48k
    Comment on it

    Description:

    Given an array of one's and zero's convert the equivalent binary value to an integer.

    Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1

    Examples:

    Testing: [0, 0, 0, 1] ==> 1
    Testing: [0, 0, 1, 0] ==> 2
    Testing: [0, 1, 0, 1] ==> 5
    Testing: [1, 0, 0, 1] ==> 9
    Testing: [0, 0, 1, 0] ==> 2
    Testing: [0, 1, 1, 0] ==> 6
    Testing: [1, 1, 1, 1] ==> 15
    Testing: [1, 0, 1, 1] ==> 11

     

     

    Solution :

    Ruby

    def binary_array_to_number(arr)
      arr.join("").to_i(2)
    end 

     

    JavaScript

    const binaryArrayToNumber = arr => {
      // your code
      return (arr[0] * 8) +
             (arr[1] * 4) +
             (arr[2] * 2) +
             (arr[3] * 1);
    };

     

    Test Cases: Ruby

     

    Test.describe("Example tests") do
    Test.assert_equals(binary_array_to_number([0,0,0,1]), 1)
    Test.assert_equals(binary_array_to_number([0,0,1,0]), 2)
    Test.assert_equals(binary_array_to_number([1,1,1,1]), 15)
    Test.assert_equals(binary_array_to_number([0,1,1,0]), 6)
    end 
    Test.describe("Random tests") do
    
    def randint(a,b) rand(b-a+1)+a end
    
    50.times do
      n = randint(0,1000)
      array = n.to_s(2).split("").map(&:to_i)
      Test.it("Tests #{array} ==> #{n}") do
      Test.assert_equals(binary_array_to_number(array), n, "It should work for random inputs too")
      end
    end
    end

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: