7. Reverse Integer

xiaoxiao2021-02-28  58

Reverse digits of an integer.

Example1: x = 123, return 321 Example2: x = -123, return -321

click to show spoilers.

Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

Subscribe to see which companies asked this question.

问题描述:将一个整数进行翻转。注:整数是32位的有符号整数,当翻转的整数溢出时返回0。

分析:无论正负整数都可以一样处理进行reverse,但要注意溢出处理。

public class Solution { public int reverse(int x) { long result=0; int a=0; while(x!=0){ a=x; result=result*10+a; x=x/10; if(result<Integer.MIN_VALUE || result>Integer.MAX_VALUE) //判断是否溢出 return 0; } return (int)result; } }

转载请注明原文地址: https://www.6miu.com/read-37203.html

最新回复(0)