LeetCode 7: Reverse Integer

刚开始并未考虑越界的问题,以及当个位数是0时会造成程序的错误,经过仔细审视,AC代码:

int reverse(int x)
{
    int res = 0;
    int temp = abs(x);

    int flag = 0;
    if (x<0)
        flag = 1;

    int shang = temp / 10;
    int yu = temp % 10;

    int over_flow = 0;
    while (shang>=0 && yu>=0)
    {
        int big_int = res * 10;
        if (res<214748364 || (res == 214748364 && flag == 0 && yu <= 7) || (res == 214748364 && flag == 1 && yu <= 8))
        {
            res = big_int + yu;
        }
        else
        {
            over_flow = 1;
            break;
        }
        temp = shang;
        shang = temp / 10;
        yu = temp % 10;
        if (shang == 0 && yu == 0)
            break;
    }

    if (over_flow)
        return 0;
    else
    {
        if (flag)
            return (-1)*res;
        else
            return res;
    }

}

 

posted @ 2015-06-01 16:04  Acode  阅读(163)  评论(0编辑  收藏  举报
您是本站第访问量位访问者!