leetcode-- Reverse Integer

来源:互联网 发布:淘宝联盟app推广教程 编辑:程序博客网 时间:2024/06/08 00:27

Reverse digits of an integer.

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

Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解:
1. c++中,对一个负数取模运算,返回值也是负数,python中,对一个负数取模运算,返回值是正的,
例如c++: -13%10=-3 python: -13%10=7
2. 对overflow的情况有多种检测方法,c++中定义不同类型所能表示的最大最小值的是头文件(limits.h)

int reverse(int x){    int result = 0;    while (x != 0)    {        int tail = x % 10;        int newResult = result * 10 + tail;        if ((newResult - tail) / 10 != result)        { return 0; }        result = newResult;        x = x / 10;    }    return result;}

    int reverse(int x) {        int sign = x < 0 ? -1 : 1;        x = abs(x);        int res = 0;        while (x > 0) {            if (INT_MAX / 10 < res || (INT_MAX - x % 10) < res * 10) {                return 0;            }            res = res * 10 + x % 10;            x /= 10;        }        return sign * res;    }};
0 0