[LeetCode] Reverse Integer 翻转整数

题目描述

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

分析

本题的难点在于对处理数据反转后可能出现的溢出情况与正负号的处理,但实际上正负号并不影响计算,方法如代码所示

#

class Solution {
public:
    int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (abs(res) > INT_MAX / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/lvquanye9483/article/details/81665512
今日推荐