LeetCode:Reverse Integer

来源:互联网 发布:ps合成图片软件 编辑:程序博客网 时间:2024/05/16 14:04

推荐参照:Leetcode题目难度等级及面试频率总结

题目描述:reverse-integer

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

思路一:

  这题的关键在于考虑反转后会存在溢出的情况。借助一中间变量来判断是否溢出。刚开始使用下面的语句进行判断,if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE),结果WA。原因是res*10后就溢出了,再用res已经是不可预期的数了,没法和真正的上下限进行比较了。

public int reverse(int x){         int res = 0;         while (x != 0){            int remainder = x % 10;             int newRes = res * 10 + remainder;             //针对溢出的检测            if ((newRes - remainder) / 10 != res)                return 0;            //检测溢出方案二在这是有问题的://           if(res >Integer.MAX_VALUE|| res < Integer.MIN_VALUE) //               return 0;            res = newRes;            x /= 10;            }         return res;    }

Runtime:43ms

思路二:

借助字符串处理整数,但是同样需要注意溢出的情况。

import java.util.*;public class Solution {    public int reverse(int x) {        String str = "";        if(x < 0){            x = -x;            str = "-";        }        String s = Integer.toString(x);        for(int i = 0; i < s.length(); i++){            str += s.charAt(s.length() - i - 1);        }        try {//捕获溢出异常等            return Integer.parseInt(str);        }catch(NumberFormatException e){            return 0;        }    }}

Runtime:49ms

Any comments greatly appreciated.

1 0
原创粉丝点击