Error in the conversion of numerical bases

Asked

Viewed 68 times

1

Well I’m asking the question 1199 Conversion of Uri bases however in some cases my test passed, only when I put a number that the staff put in the forum gave error, the number was 0x80000000 the expected result is 2147483648, only that my code prints -2147483648, I have tried to multiply by -1 and the result remains negative, someone could help me

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char saber_o_tipo(char *numero);

int main(int argc, char** argv)
{
   char *numero;
   numero = (char*)malloc(sizeof(char) * 1000000);
   int resposta, valor;
   while(1)
   {
     scanf("%s", numero);
     if(numero[0] == '-')
     {
        break;
     }
     resposta = saber_o_tipo(numero);
     if(resposta > 0)
     {
        sscanf(numero, "%x", &valor);
        if(valor < 0)
        {
            printf("%d\n", valor*-1);
        }
        else
        {
            printf("%d\n", valor);
        }
     }
     else
     {
        sscanf(numero, "%d", &valor);
        printf("Ox%X\n", valor);
     }
 }
  free(numero);
  return 0;
}

char saber_o_tipo(char *numero)
{
  int i, contador = 0, tamanho;
  tamanho = strlen(numero);
  for(i = 0; i < tamanho; i++)
  {
     if(isalpha(numero[i]))
     {
        contador++;
     }
  }
  if(contador > 0)
  {
     return 1;
  }
  else
  {
     return 0;
  }
}

1 answer

1

The memory space used by an integer (32 bits) can store numbers in the range of -2,147,483,647 up to 2,147,483,647.

To work with a longer range use the long long type instead of int.

Note that the description of the problem states: "The decimal value will be less than or equal to 2 31".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.