Leecode #7 Reverse Integer

一、 问题描述
Leecode第七题,题目为:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21

问题理解为

给定一个32位带符号整数,对其进行翻转运算。

二、解题思路

x % 10:求余
x /= 10:除法

三、实现代码

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/serena_t/article/details/90054138