最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

7. Reverse Integer

XAMPP新闻 admin 1280浏览 0评论

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: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

难度:easy

题目:
给定32位带符号整数,反转该整数。

注意:
假定处理的环境只能存储32位带符号整数范轩为[负的2的32次方, 2的32次方-1]。 这个问题的目的在于溢出的整数返回0.

思路:两次反转,如果不变则没有溢出,如果不同分为两种情况一种是变之前尾数有0的,另一种则是溢出的。

Runtime: 16 ms, faster than 97.34% of Java online submissions for Reverse Integer.

public class Solution {
public int reverse(int x) {
int result = justReverse(x);
int reverseResult = justReverse(result);
// 120 -> 21 -> 12, so x % reverseResult == 0 is also not overflow
return reverseResult == x || x % reverseResult == 0 ? result : 0;

}

private int justReverse(int x) {
int result = 0;
while(x != 0) {
int m = x % 10;
x = x / 10;

result = result * 10 + m;
}

return result;
}
}

转载请注明:XAMPP中文组官网 » 7. Reverse Integer

您必须 登录 才能发表评论!