Given an integer number n, we want to reverse its digits. We are not allowed to use extra memory like arrays to do this. We have to do it only using antiemetics.
Example:
n = 123
Ans: 321
Solution:
We want to make sure we handle negative integers first. To do that we just multiply the number by -1 to make it positive.
The trick here is to understand the formula here
reverse = (reverse * 10) + (n%10); where reverse = 0 initially and it got the new value every time we divide n by 10
public int Reverse(int x) {
long reverse = 0;
long n = (x<0)? -1*x: x;
while(n > 0) {
rev = (reverse * 10) + (n%10);
n/=10;
}
if(reverse > Int32.MaxValue)
return 0;
return (x<0)? (int)(-1*rev): (int)reverse ;
}