C++

Example of C++ conversion of interview questions


An instance of C++ base conversion

One interview question requires input of base 10 number and output of base 106. It can be printed with printf %d,%c,%s, but cannot be printed with %x.

I’ve written two algorithms, which are pretty neat, and I’ll paste them here.

//  The first 1 Kind of algorithm, scan shift from low to high, required 1 Two arrays in reverse order, 1 Secondary output

#include <stdio.h>

#define MAX_HEX_NUM 16
#define OUT_DATA_LEN sizeof(int)*2 // 2 a 16 Base number representation 1 bytes

static char Hex_Char_Table[MAX_HEX_NUM] = {
  '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};

int ten2hex( int data )
{
  char result[OUT_DATA_LEN+1];
  int i,index;

  result[OUT_DATA_LEN] = '\0';
  for( i=OUT_DATA_LEN-1; i>=0; i-- )
  {
    index = data & 0xf;
    result[i] = Hex_Char_Table[index];
    data = data>>4;
  }

  printf("0x%s\n",result);

  return 0;
}

Here is the second algorithm, which scans from the top to the bottom and prints the results directly.

#include <stdio.h>

#define BITS_OF_INT  sizeof(int)*8 // int Number of bits
#define OUT_DATA_LEN sizeof(int)*2 // 2 a 16 Base number representation 1 bytes

int printHex( int num )
{
  int i;

  printf("0x");
  for(i=0;i<OUT_DATA_LEN;i++)
  {
    unsigned int res = num & 0xf0000000; // Note: must be used  unsigned int To receive, otherwise you will get a conversion error when you enter a negative number
    res = res >> (BITS_OF_INT-4);
    char c;
    if( res <= 9 )
      c = res + '0';
    else
      c = 'A' + res - 10;

    printf("%c",c);

    num = num << 4;
  }

  printf("\n");
}

Both of these algorithms actually use a shift instead of a division, which is much more efficient, and I think the point of the problem is here.

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!