Wednesday, January 27, 2021

Concatenation of binary representation of two numbers

Problem: Given two integers x and y the task is to find the number formed by concatenating the binary equivalents of x and y.

Example:

Input: x = 1, y = 2
Output: 6
Explanation: 1's in binary representation is 1 and 2's binary representation is 10. After concatenation it will become 110 which is 6.   


Approach: We can binary shift the x with the number of bits in y and then OR it with y. Say x is 1 and y is 2. The number of bits in y is 2. So we will shift x by 2. Now x will become:

x << 2 = 1 << 2 = 100

x OR y = 100 OR 10 = 110 = 6


Implementation in C#:

        public int Concat(int x, int y)

        {

            int numOfBits = this.NumOfBits(y);

            x <<= numOfBits;

            return x | y;

        }


        private int NumOfBits(int num)

        {

            int numOfBits = 0;

            while(num != 0)

            {

                num /= 2;

                ++numOfBits;

            }

            return numOfBits;

        }


Complexity: O(log(y))

No comments:

Post a Comment