Search code examples
mathbinarydecimalcomputer-science

How to convert 10^4 to binary


I need to convert 10^4 to binary

expanding it will give me a large number and dividing that by 2 a bunch of times will be really inefficient

10^4 = 10000

how do i do it directly


Solution

  • I would write a recursive function, the pseudo-code is here:

    int Convert_to_binary (x):
         if(x == 0):
            return 1;
         if(x == 1):
            return 10;
         if(x%2 == 1):
            return Convert_to_binary(x-1)+1;
         if(x%2 == 0):
            return Convert_to_binary(x/2)*10;
    

    This will return the binary format as an integer like 2 is 10 in binary and 1 is 1 in binary format and 3 is 11 and so on