Example1: x = 123, return 321
Example2: x = -123, return -321
挺简单的一个题目,只需要分情况讨论即可,因为一个int型数据可能是正数可能是负数,也可能为0,当然还有一种很重要的情况就是溢出,当实参大于int的最大值的情况下的处理,直接返回0即可
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;
  }
};这道题教会我考虑对于一个问题,我们要考虑各种边界情况,比如为0,比如溢出...










