# Reverse digits of an integer.

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

class Solution {
public:
int reverse(int x) {
if (x == 0)
{
return x;
}
bool negative = false;
if (x < 0)
{
negative = true;
x = 0 - x;
}
//检测该x是否已经溢出，溢出时直接返回0
int max = numeric_limits<int>::max();
if (x>max)
return 0;
//到此为止，x已经是非负值了
int nBits = 1, nAverage = 10;
int tmp = x;
while (true)
{
if (nAverage == 1000000000)
{
if ((tmp / nAverage<10)&&(tmp/nAverage!=0))
{
nBits++;
break;
}
}
if (tmp / nAverage)
{
nBits++;
nAverage *= 10;
}
else
break;
}
//到现在为止 nBits是和x位数一致，nAverage和x的位数也是一致的
int* nArray = new int[nBits];
int  nCount = 0;
tmp = x;
if (nBits != 10)
{
//如果nBits不为0，也就是肯定没有溢出的情况下，则nAverage的值是多乘了一个10，进行矫正
nAverage /= 10;
}
while (nCount<nBits)
{
nArray[nCount++] = tmp / nAverage;
tmp -= nAverage*nArray[nCount - 1];
nAverage /= 10;
}
//进行新数组的构造，作为返回值应该是防止溢出的，所以定义为unsigned long long，在int型数据下操作是没有问题的，
unsigned long long sum = 0;
for (int i = 0; i < nBits; i++)
{
unsigned long long mm = 1, m = 0;
while (m!=i)
{
mm *= 10;
m++;
}
sum += (unsigned long long)nArray[i] * mm;
if (sum>max)
return 0;
}
delete[] nArray;
if (negative)
{
sum = 0 - sum;
}
return sum;
}
};

02-16 3167

10-20 664

09-09 2133

10-28 81

06-24 190

09-02 486

02-26 136

08-13 123

03-22 1040

12-15 67