题目来源于 LeetCode 上第 7号(Reverse Integer)问题,题目难度为 Easy,AC率25.4%git
题目地址:https://leetcode.com/problems/reverse-integer/面试
Given a 32-bit signed integer, reverse digits of an integer.算法
给定一个32位带符号整数,反转整数数组
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
复制代码
Note:bash
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.函数
假设只能存储32位带符号整数范围内的整数:[- 2 ^31 , 2 ^31 - 1]。假设函数在反向整数溢出时返回0。post
整数x的取值范围是:-2 ^31 ~ 2 ^31 - 1(-2147483648~2147483647),假设咱们输入的整数是1234567899,reverse后就变成了9987654321,超出int最大范围,也就会出现越界错误,因此咱们应该定义一个long型的变量sum来存储反转以后的数字ui
经过不断的取余运算,从整数的末尾开始,一位一位的移动生成新的数字this
算法效率以下: spa
public int reverse(int x) {
long sum = 0;
while(x != 0){
sum = sum*10 + x%10;
x = x/10;
if(sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) return 0;
}
return (int)sum;
}
复制代码