Click here to Skip to main content
15,665,276 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi i want to get reverse of a number in c#
Posted
Comments
Sergey Alexandrovich Kryukov 11-Jan-12 1:12am    
Please, define reversed number. And why not implementing it by yourself?
--SA

Let me help you get thinking. You can try writing the code yourself.

Divide the number by 10 and take the mod (remainder) value. You get the first digit.
Now divide the number by 10 and ignore the part after the decimal.
Divide the number by 10 again and take the mod value. You get the second digit.
Now divide the number by 10 and ignore the part after the decimal.
And so on...till you have got all the digits.

Now place them all in the reverse order and print them out (if you want to use string operations).

If you don't want to use string operations, you can start multiplying the last digit by 10.
Then the second last by 10*10 = 100
Then the third last by 10*10*10= 1000
And so on....

Finally add this result and you will get the reversed number.
 
Share this answer
 
v2
Comments
chandrashekhar racharla 11-Jan-12 0:38am    
Nice Explanation take +5
Abhinav S 11-Jan-12 0:40am    
Thank you.
Hi,
Try this;
C#
int n = 12345;
int left = n;
int rev = 0;
while(left>0)
{
  r = left % 10;
  rev = rev * 10 + r;
  left = left / 10;
}

Console.WriteLine(rev);


And the best example with snaps on following link:
Reverse[^]
 
Share this answer
 
v2
C#
public int ReverseInt(int num)
{
    int result=0;
    while (num>0)
    {
       result = result*10 + num%10;
       num /= 10;
    }
    return result;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900