Free image from unsplash.com

C Kata - Convert a Number to string!

By Lochard | As a newbie programmer | 10 Oct 2022


Learning from YayoDrayber, I am sharing my CodeWars Kata.

 

DESCRIPTION

We need a function that can transform a number (integer) 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 (input --> output):

123 --> "123"

999 --> "999"

-100 --> "-100"

Starting code

#include <stdlib.h>

char *number_to_string(int number) {
    // <---- hajime!
  return calloc(1, 1); // memory will be freed
}

My solution

#include <stdlib.h>

char *number_to_string(int number) {
  int len = 1, worker = number;

  while (worker / 10 != 0) {
    len++;
    worker /= 10;
  }

  if (number < 0)
    len++;

  char *ret = calloc(len, sizeof(char));

  if (number < 0) {
    ret[0] = '-';
    number *= -1;
  }

  do {
    ret[--len] = '0' + number % 10;
    number /= 10;
  } while (number != 0);

  return ret;
}

Wanted to do it the basic way. Messed up hard and spent a lot of time. The thumbnail couldn't be more suitable for my attempts.

 

Best Practices + Clever + My Pick + My post-Kata snippet

#include <stdio.h>
const char* number_to_string(int number) {
  char *s; asprintf(&s, "%d", number);
  return s;
}

Nice and short with the asprintf we have learned in a previous lesson.

 

My code snippets on GitHub

How do you rate this article?

5


Lochard
Lochard

20240228 Arrived in the UK for about 2 week. All my fears persist. Some are even getting worse. https://github.com/locharp/asylum_diary/


As a newbie programmer
As a newbie programmer

Sharing entry level codes. My snippets on GitHub https://github.com/locharp/code-snippets

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.