@Fraidy Levilev
What compiler are you using? C++ requires a return from a non-void function, but the for loop looks like C++. As it stands, I can't tell where your value of 1969647184 is coming from.
Your original example looks totally correct. But I would paraphase point 5 of your follow on explanation so it reads "5. continues until you have
no more digits to reverse."
This suggests that the loop termination condition (as you orig intended, a while loop is the right way to go here) is something to do with 0.
But, as mentioned by earlier posters, your code's loop isn't quite right, and you're overwriting x with the value of uninitialized valiable, etc. The suggestions to count the numbers first are a bit of a red herring, though.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
int reverse(int x)
{
int a, b = 0, c; // b must be init to zero
//for (int i=0; i<0; i++)
while(x > 0)
{
//x=a; -- not needed
a=x%10;
//b=i*10+a; -- not quite right: replace i with b
b = b * 10 + a; // multiply b by 10, to shift existing
// digits to the left, and add new units value
c=x/10;
x = c; // ready for the next iteration
}
return b;
}
|
Or, eliminating debris and unnecessary variables
1 2 3 4 5 6 7 8 9 10 11 12 13
|
int reverse(int x)
{
int b = 0;
while(x > 0)
{
int a = x % 10;
b = b * 10 + a;
x = x / 10; // ready for the next iteration
}
return b;
}
|
Or even more succinctly, and tweaking the termination condition so negative values are also handled.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int reverse(int val)
{
int rev_val = 0;
while(val != 0)
{
// shift digits in reversed value one left and add on
// new units value
rev_val = rev_val * 10 + val % 10;
// shift value one to right, losing current units value,
// ready for the next iteration
val /= 10;
}
return rev_val;
}
|