LeetCode之Reverse Integer
【摘要】 1、题目
Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 click to show spoilers. Note: The input is assumed to be a 32-bit signed inte...
1、题目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
2、代码实现
代码实现1、
通过不了LeetCode
-
public static int reverse(int x) {
-
if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
-
return 0;
-
}
-
boolean flag = false; //x是负数就是true,正数false
-
if (x < 0) {
-
flag = true;
-
}
-
String string = String.valueOf(x);
-
String spliteStr = flag ? string.substring(1) : string;
-
StringBuffer sb = new StringBuffer(spliteStr);
-
sb = sb.reverse();
-
String result = sb.toString();
-
result = flag ? "-" + result : result;
-
long value = Long.valueOf(result);
-
if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) {
-
return 0;
-
}
-
return (int)value;
-
}
代码实现二、
通过不了LeetCode
-
public static int reverse1(int x) {
-
if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
-
return 0;
-
}
-
long result = 0;
-
int temp = Math.abs(x);
-
while (temp > 0) {
-
result *= 10;
-
result = result + temp % 10;
-
temp /= 10;
-
}
-
-
if (result > Integer.MAX_VALUE ||result<Integer.MIN_VALUE ) {
-
return 0;
-
}
-
return (int)(x >= 0 ? result : -result);
-
}
代码实现三
可以通过LeetCode
-
public static int reverse3(int n) {
-
if (n > Integer.MAX_VALUE || n < Integer.MIN_VALUE) {
-
return 0;
-
}
-
//输出结果定义为long
-
long sum=0;
-
while (n != 0) {
-
int s = n % 10;
-
sum = sum * 10 + s;
-
n = n / 10;
-
}
-
//防止溢出操作
-
if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) {
-
return 0;
-
}
-
return (int)sum;
-
}
注意有溢出问题,对比分析,第一个实现和第二个实现 不越界没问题。
文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。
原文链接:chenyu.blog.csdn.net/article/details/65631346
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)