整数反转

题目描述:给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [LeetCode-007-整数反转 - 图1, LeetCode-007-整数反转 - 图2 − 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:字符串遍历

首先获取整数的符号symbol,然后将整数部分转换成字符串,从后往前遍历,得到反转后的字符串result,将symbol和result拼起来就是最终的返回结果。

注意点:考虑转化后的值是否超过整数的范围,如果超过了,返回0。

  1. public class Solution {
  2. public static int reverse(int x) {
  3. if (x == 0 || x < Integer.MIN_VALUE || x > Integer.MAX_VALUE) {
  4. return 0;
  5. }
  6. String xStr = String.valueOf(x);
  7. String symbol = "";
  8. if (x < 0) {
  9. symbol = "-";
  10. xStr = xStr.substring(1);
  11. }
  12. String result = "";
  13. int zeroCount = 0;
  14. for (int i = xStr.length() - 1; i >= 0; i--) {
  15. if (xStr.charAt(i) != '0') {
  16. break;
  17. } else {
  18. zeroCount++;
  19. }
  20. }
  21. for (int i = xStr.length() - 1 - zeroCount; i >= 0; i--) {
  22. result += xStr.charAt(i);
  23. }
  24. double doubleResult = Double.valueOf(symbol + result);
  25. if (doubleResult < Integer.MIN_VALUE || doubleResult > Integer.MAX_VALUE) {
  26. return 0;
  27. }
  28. return Integer.valueOf(symbol + result);
  29. }
  30. public static void main(String[] args) {
  31. System.out.println(reverse(123));
  32. }
  33. }