#7 Reverse Integer

来源:互联网 发布:浙大中控的java 编辑:程序博客网 时间:2024/05/21 23:01

题目链接:https://leetcode.com/problems/reverse-integer/


Reverse digits of an integer.

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

click to show spoilers.

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.


int reverse(int x) {    long long ret = 0;    int digit;    while(x) {        digit = x > 0 ? x % 10 : -(-x) % 10;        ret = 10 * ret + digit;        if(ret > 2147483647 || ret < -2147483648)            return 0;        x /= 10;    }        return ret;}



0 0
原创粉丝点击