Leetcode:7. Reverse Integer

7. Reverse Integer

题目:
Leetcode:7. Reverse Integer

描述:

  • 内容:Reverse digits of an integer.
    Example1: x = 123, return 321
    Example2: x = -123, return -321
  • 题意:判断输入的一个有符号整型数字,倒序输出

分析:

  • 思路如下:
    1. 将每个字符存储,%取余 整除取出每一个数位的大小;
    2. 对于取出来的每个数位进行反向组合 12132 -》23121,这里特别说明使用long long存储;
    3. 如何判断越界问题:long long 存储数据与 INI_MAX INI_MIN边界对比,越界则返回0;
    4. 备注: limits.h 中有define INI_MAXINI_MIN

代码:

int reverse(int x) {
    if (x < 10 && x > -10)
    {
        return x;
    }

    vector<int> vecNum(10, 0); // 十位数字存储即可
    int nIndex = 0;
    while (0 != x)
    {
        vecNum[nIndex++] = x % 10;
        x /= 10;
    }

    int nBgn = 0;
    long long nTemp = 0;
    while (nBgn < nIndex)
    {
        nTemp = nTemp * 10 + vecNum[nBgn];
        ++nBgn;
    }

    if (nTemp > INT_MAX || nTemp < INT_MIN)
    {
        return 0;
    }

    return nTemp;
}

备注:

原文地址:https://www.cnblogs.com/liuwfuang96/p/6859085.html