题目描述
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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
翻转整数,如果越界了就返回 0。
解题思路
转换成字符串,用 long 存储检查大小。
代码
class Solution { public int reverse(int x) { String tmp = String.valueOf(x); long ret = 0; for (int i = tmp.length()-1; i >= 0; i--) { if (i == 0 && tmp.charAt(i) == '-') { ret *= -1; } else if (i == 0 && tmp.charAt(i) == '+') { break; } else if (tmp.charAt(i) >= '0' && tmp.charAt(i) <= '9') { ret *= 10; ret = ret + tmp.charAt(i) - '0'; } else { return 0; } } if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) return 0; return (int)ret; } }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于