I need to make a program that the user type a three-digit number and the program reverses that number for example 123 -> 321
, I would like to know the logic to do this, because I can not think of anything.
I need to make a program that the user type a three-digit number and the program reverses that number for example 123 -> 321
, I would like to know the logic to do this, because I can not think of anything.
If you want to understand how the algorithm works for a function that does the rollback:
#include <stdio.h>
#include <string.h>
void reverse(char str[]) {
int len = strlen(str) ;
char tmp;
for (int i = len / 2; i >= 0; i--) {
tmp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = tmp;
}
}
int main(void) {
char str[] = "123";
reverse(str);
printf("%s", str);
}
See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .
Doing by math:
#include <stdio.h>
#include <math.h>
int reverse(int num) {
int inv = 0;
int dig = 0;
for (int i = 2; i >= 0; i--) {
dig = num / (int)pow(10.0, (double)i); //infelizmente C não tem uma função de potência para inteiro
num -= dig * (int)pow(10.0, (double)i);
inv += dig * (int)pow(10.0, (double)(2 - i));
}
return inv;
}
int main(void) {
printf("%d", reverse(123));
}
See running on ideone . Also put it in GitHub for future reference .
If you need a function that reverses arbitrary size:
int inverte(int x) {
int inv = 0;
while (x > 0) {
inv = 10 * inv + x % 10;
x /= 10;
}
return inv;
}
What does it do and get the rest of the division of the number by 10, that is, the digit to the right of the number and add with the number that we have until the moment times 10.
For example, if we are to invert 23:
inv = 0
resto de 23 por 10 == 3
inv = 10 * inv + 3 == 3
dividimos 23 por 10 == 2
repetimos:
inv = 10 * inv + 2 % 10 == 10 * 3 + 2 == 32
For the exact conditions of the problem, this is enough:
str[0] ^= str[2];
str[2] ^= str[0];
str[0] ^= str[2];
See working at IDEONE
str[0] ^= str[2] ^= str[0] ^= str[2];
See working at IDEONE
int i, len = strlen( str );
for ( i = len / 2; i >= 0; i--)
str[i] ^= str[len - i - 1] ^= str[i] ^= str[len - i - 1];
See working at IDEONE
I put it as "algorithmic curiosity", since the two solutions posted solve the problem well, in the traditional way. To find out how this solution works, strong> this question . (tip of @bfavaretto)