Algorithm 11 - Convert a Number to a String!

Beast from the east·2021년 10월 6일
0

Algorithm

목록 보기
11/27

Q.

Description:
We need a function that can transform a number into a string.

What ways of achieving this do you know?

In C, return a dynamically allocated string that will be freed by the test suite.

Examples:
123 --> "123"
999 --> "999"

A)

#include <stdlib.h>

const char* number_to_string(int number)
{
  char *ptr;
  int len = 0;
  long long nb = (long long)number;
  
  if (number < 0)
    nb *= -1;
  
  while (nb != 0)
  {
    nb = nb / 10;
    len++;
  }
  
  if (number > 0)
    ptr = (char*)malloc(sizeof(char) * len + 1);
  else
  {
    len++;
    ptr = (char*)malloc(sizeof(char) * len + 1);
  }
  
  if (!ptr)
    return NULL;
  
  ptr[len] = '\0';
  
  nb = (long long)number;
  
  if (number < 0)
    nb *= -1;
  
  while (len--)
  {
    ptr[len] = '0' + (nb % 10);
    nb /= 10;
  }
  
  if (number < 0)
    ptr[0] = '-';
  
  return ptr;
}

another solution
#include <stdio.h>

const char* number_to_string(int number) {
    char *s;
    asprintf(&s, "%d", number);
    return s;
}

another solution
#include <stdlib.h>

const char* number_to_string(int number) {
    char *itoa = malloc(256);
    sprintf(itoa, "%d", number);
    return itoa;
} -> sprintf() function으로 첫 매개변수에 받는 버퍼에 number를 문자열로 저장하는 듯.

another solution
#include <stdlib.h>

const char* number_to_string(int number) {

    size_t bufferLength = snprintf(NULL, 0, "%d", number); //Find the length of the string conversion
    char* buffer = malloc(bufferLength + 1); //dynamically allocate the string
    
    snprintf(buffer, bufferLength + 1, "%d", number); //populate the string
    
    return buffer; //return the string
}
profile
Hello, Rabbit

0개의 댓글