reverse-integer

本文介绍了一种用于反转整数的有效算法,并讨论了处理负数及溢出情况的方法。该算法通过将输入整数的每一位逐个提取并重新组合来实现反转,同时确保结果在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).

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

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

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

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%10;
			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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值