LeetCode:Reverse Integer(反转整数)

xiaoxiao2021-02-28  48

题目

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

Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

思路

主要难点在于溢出问题。要判断是否溢出,因此定义了long类型的变量来存储反转后的数,然后判断是否溢出。可以直接通过INT_MAX获取int的最大值,也就是题目要求的2^32-1。为了简便反转处理中先省略了符号,在最后再填上。

代码

class Solution { public: int reverse(int x) { long res=0; int sig=1; if(x<0) sig=-1; while(x) { int temp=x%10; if(temp<0) temp=-temp; if(!res) { if(temp) res=res*10+temp; } else res=res*10+temp; x/=10; } if(res>INT_MAX) return 0; return res*sig; } };
转载请注明原文地址: https://www.6miu.com/read-2626235.html

最新回复(0)