Reverse Integer

来源:互联网 发布:怎样看降没有降权淘宝 编辑:程序博客网 时间:2024/05/12 16:15

Reverse Integer

Reverse digits of an integer.

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

算法思路

先求出整数有多少位,然后将其反转,但是需要注意反转后的数是否越界,如果越界,直接返回0

代码实现

class Solution {public:    int reverse(int x) {    const int max = 0X7FFFFFFF;    const int min = 0X80000000;    long long rslt = 0;    //获取x位数    int count = 0;    int temp = x > (-x) ? x : (-x);    while (temp > 0)    {        temp = temp / 10;        ++count;    }    temp = x;    int digit = count;    int judge = 0;  //初始化judge为0    while (count >= 1)    {        int num = temp % 10;        int index = count - 1;        long long as = 1;        while (index >= 1)        {            as = as * 10;            --index;        }        rslt += num*as;        temp = temp / 10;        --count;    }    if (rslt > max || rslt < min)        return 0;    return static_cast<int>(rslt);}};
1 0