Domanda

Is there a library function or easy way of reading a number backwards and operating with it? By operating, I mean do operations with the new number.

For example:

2845
would become
5482

How can you achieve that? I've had an idea where you could do a digit[i] array, null by default and receive as many values as the number has. For example 452 would give digit[3] : digit[1] would be 4, digit[2] would be 5, and digit[3] would be 2. But that sounds awfully complicated and printing it sounds like a pain in the butt, not to mention I couldn't operate with the new digit. I need to check if the number read backwards is even.

Any ideas? I've been thinking on this one for quite a while, but I can't figure out a proper solution. Also if it matters, I'm using eclipse IDE in the C language.

È stato utile?

Soluzione

A simple solution would be:

/* only for x>0 */
int reverse(int x)
{
    int r = 0;
    while(x) {
        r = r*10 + (x%10);
        x = x/10;
    }

    return r;
}

Altri suggerimenti

If you're dealing with small enough numbers, maybe just read it into a C string, use strrev() and then convert to an integer? Although, if all you have to do is to "check if the number read backwards is even", all you really have to do is to check if the first character is '0', '2', '4', '6', or '8'.

I'd use sprintf() to convert it to a char*, reverse it with some simple arithmetic, then use strtol() to convert it back again.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top