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.