Code to concatenate two numbers' bits not working

后端 未结 3 1020
自闭症患者
自闭症患者 2021-01-14 14:16

The task is to concat the binary of 2 given numbers.

Example:

Given 5 (101) and 3 (011),

3条回答
  •  [愿得一人]
    2021-01-14 14:57

    I don't know what language you are using, it's almost Java, so I am going with that.

    This returns the result you are asking for, though you haven't given rules for determining how you know that 3 should be 011 instead of 11.

    I have made the assumption that you want to assume that both numbers have the same number of bits, so 3 is 011 because 5 requires 3 bits.

    public class Concat {
      public static void main(String[] args) {
        System.out.println( joinNums(3,5) );
      }
    
      public static int numBits( int n ) { 
        return (int)Math.ceil( Math.log(n) / Math.log(2) );
      }
    
      public static int joinNums( int num1 , int num2 ) {
        int bits = Math.max( numBits(num1) , numBits(num2) );
        return (num1 << bits) + num2;
      }
    }
    

提交回复
热议问题