LeetCode-007 Reverse Integer

来源:互联网 发布:java前端面试题 编辑:程序博客网 时间:2024/06/05 14:12

Description

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

Example

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Analyse

一道水题,将一个有符号整数反转,但需要注意的是,反转之后可能越界,这里投机取巧的方式就是让答案设为64位,若越界则返回0,否则强制类型转换回整型即可。

Code

class Solution {public:    int reverse(int x) {        long ans=0;        while (x!=0) {            ans=ans*10+x%10;            x=x/10;            if (ans>INT_MAX || ans<INT_MIN) return 0;        }        return (int) ans;    }};