Reverse Integer - LeetCode

题目链接

Reverse Integer - LeetCode

注意点

  • 要考虑到正负数溢出的情况不同
  • 注意不要把负数转为正数来做,因为溢出的范围不一样

解法

解法一:从后往前,每次翻转一位,anw记录上一轮翻转的结果,temp记录新的翻转结果,如果得到的翻转结果溢出,除以10不会等于上一轮翻转的结果anw。时间复杂度为O(n)

class Solution {
public:
    int reverse(int x) {
        int anw = 0;
        while(x != 0)
        {
            int temp = anw*10 + x%10;
            if(temp/10 != anw)
            {
                return 0;
            }
            anw = temp;
            x /= 10;
        }
        return anw;
    }
};

小结

  • int的取值范围是[-231,231-1]也就是[-2147483648,2147483647]
posted @ 2019-01-22 13:35  闽A2436  阅读(114)  评论(0编辑  收藏  举报