Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

C++:
01 class Solution {
02 public:
03     int reverse(int x) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         int sign=1;
07         if(x<0)
08         {
09             sign=-1;
10             x=-x;
11         }
12         int y=0;
13         while(x!=0)
14         {
15             int tmp=x%10;
16             x=x/10;
17             y=y*10+tmp;
18         }
19         return y*sign;
20     }
21 };
Advertisements
This entry was posted in Array and linked list, Number trick. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s