Reverse Integer

来源:互联网 发布:和合期货软件下载 编辑:程序博客网 时间:2024/05/17 18:49

题目:Reverse digits of an integer.

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

思路:迭代计算,保存末尾值。注意一开始的负号

第一个需要注意的就是判断最大值最小值,尤其是最小值,这一点在后面的求解除法中非常明显。

代码:

class Solution {public:<span class="comment" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);">//for more information,please email:j.z.feng@foxmail.com</span><span style="margin: 0px; padding: 0px; border: none; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);"> </span>//https://leetcode.com/problems/reverse-integer/    int reverse(int x) {        if(x<0){            return x==INT_MIN ? 0 : -reverse(-x);        }        int y,result=0;        //x=32767        if(x==0){            return 0;        }        while(x>0){            if(result>INT_MAX/10){                return 0;            }            if(result==INT_MAX/10 && (x%10)>7){                return 0;            }            result=result*10+(x%10);            x=x/10;        }        return result;    }};


0 0
原创粉丝点击