Reverse Integer

Description:

Reverse digits of an integer.

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

Code:

 1   int reverse(int x) {
 2         int p=0;
 3         int temp = x;
 4         while (temp)
 5         {
 6             temp /= 10;
 7             p++;
 8         }
 9         temp = 0;
10         for (int i = p-1; i >= 0; i--)
11         {
12             // 判断溢出
13             if ( temp + (x%10)*pow(10.0,i) > INT_MAX || temp + (x%10)*pow(10.0,i) < INT_MIN )
14                 return 0;
15             temp += (x%10)*pow(10.0,i);
16             x=x/10;
17         }
18         return temp;
19     }

 

posted @ 2015-06-14 19:57  Rosanne  阅读(207)  评论(0编辑  收藏  举报