C - reverse a number

后端 未结 6 1186
时光取名叫无心
时光取名叫无心 2020-12-18 05:58

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,

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-18 06:36

    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');
    }
    

提交回复
热议问题