reverse-integer

xiaoxiao2021-02-28  33

题目描述 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).

//首先要考虑溢出问题,如果溢出,就只能取最接近的值,然后这个值必须得由long来保存,才可能保存得到溢出值。

//以及在获取相反结果的时候每次都乘以10加x就可获得反转的数。

//这是我写的拙劣的代码

import java.util.ArrayList; public class Solution { public int reverse(int x) { int res = 0 ; ArrayList<Integer> result = null; if(x==0)return 0; if(x<0) { x = -x; result = result(x); for (int i = 0; i < result.size(); i++) { res+=result.get(i)*Math.pow(10, result.size()-i-1); } res=-res; }else { result = result(x); for (int i = 0; i < result.size(); i++) { res+=result.get(i)*Math.pow(10, result.size()-i-1); } } return res; } public ArrayList<Integer> result(int x) { ArrayList<Integer> list = new ArrayList<Integer>(); while(x>0) { int r = x; x=x/10; list.add(r); } return list; } }

//这是我觉得考虑全面的安全最高的代码

public class Solution { public int reverse(int x) { int flag = x < 0 ? -1 : 1; x *= flag; long res = 0; while (x > 0) { res = res * 10 + x % 10; x /= 10; } if (flag * res > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (flag * res < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return (int) (res * flag); } }
转载请注明原文地址: https://www.6miu.com/read-2650058.html

最新回复(0)