Leetcode-reverse-integer

来源:互联网 发布:网络的英文翻译 编辑:程序博客网 时间:2024/06/05 16:32

题目描述

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

leetcode上的题目就是各种限制条件多,注意下方的那些提示,有些方法是不能用的。

public class Solution {    public int reverse(int x) {        boolean isfu = false;        if(x == 0)return 0;if(x < 0){x = Math.abs(x);isfu = true;}String str = String.valueOf(x);char[] charArray = str.toCharArray();int n = charArray.length;for(int i=0; i<n/2; i++){char temp = charArray[i];charArray[i] = charArray[n-1-i];charArray[n-1-i] = temp;}String res = "";int j  = 0;for(int i=0; i<n; i++){if(charArray[i] != '0'){break;}j++;}for(int i=j; i<n; i++){res += charArray[i];}int s = Integer.parseInt(res);if(isfu){return 0-s;}else{return s;}    }}
首先:是负数的标记出来,并转为正数处理。

其次,倒置处理结束后,寻找到第一个不是0的位置,把该位置后面的所有的数字全部输出出来即可。

最后,如果是负数,则加上符号,不是则输出上述结果。

0 0
原创粉丝点击