I am coding in C on linux, and I need to reverse a number. (EG: 12345 would turn into 54321), I was going to just convert it into a string using itoa and then reverse that,
iota()
is not a standard C function, but snprintf()
serves the purpose just as well.
/* assume decimal conversion */
const char * my_itoa (int input, char *buffer, size_t buffersz) {
if (snprintf(buffer, sz, "%d", input) < sz) return buffer;
return 0;
}
Since the input cannot be negative, you can use an unsigned type:
unsigned long long irev (unsigned input) {
unsigned long long output = 0;
while (input) {
output = 10 * output + input % 10;
input /= 10;
}
return output;
}
Reversing the input may result in a value that no longer fits the input type, so the return result attempts to use a wider type. This may still fail if unsigned
and unsigned long long
have the same width. For such cases, it is probably easiest to use a string to represent the reversed value. Or, if the only goal is to print the number, you can just use a loop to print the digits in reverse order.
void print_irev (unsigned input) {
if (input) {
do {
putchar('0' + input % 10);
input /= 10;
} while (input);
} else {
putchar('0');
}
putchar('\n');
}