首页 > ACM题库 > LeetCode > LeetCode-Reverse Integer
2014
07-22

LeetCode-Reverse Integer

Reverse digits of an integer.

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

注意事项

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).

题目并不难,如果是在面试中,能先提出下面这些问题是加分项:

1) 如果数字的末尾是0,如何处理? 例如 100,输出1还是001?

2)是否要考虑溢出?例如对于int类型,1000000003 翻转后会溢出。

3)处理处理这些错误,抛出异常吗?

代码本身并没有什么难度,参考如下

public class Solution {
    public static int reverse(int x){
		if(x==Integer.MIN_VALUE)  
	        return Integer.MIN_VALUE;
		int ans = 0;
		int tmp = Math.abs(x);
		while(tmp > 0){
			int b = tmp % 10;
			ans = ans*10 + b;
			tmp /= 10;
		}
		return x > 0 ? ans:-ans;
	}
}

  1. 其实国内大部分公司对算法都不够重视。特别是中小型公司老板根本都不懂技术,也不懂什么是算法,从而也不要求程序员懂什么算法,做程序从来不考虑性能问题,只要页面能显示出来就是好程序,这是国内的现状,很无奈。

  2. 第二个方法挺不错。NewHead代表新的头节点,通过递归找到最后一个节点之后,就把这个节点赋给NewHead,然后一直返回返回,中途这个值是没有变化的,一边返回一边把相应的指针方向颠倒,最后结束时返回新的头节点到主函数。

  3. for(int i=1; i<=m; i++){
    for(int j=1; j<=n; j++){
    dp = dp [j-1] + 1;
    if(s1.charAt(i-1) == s3.charAt(i+j-1))
    dp = dp[i-1] + 1;
    if(s2.charAt(j-1) == s3.charAt(i+j-1))
    dp = Math.max(dp [j - 1] + 1, dp );
    }
    }
    这里的代码似乎有点问题? dp(i)(j) = dp(i)(j-1) + 1;这个例子System.out.println(ils.isInterleave("aa","dbbca", "aadbbcb"));返回的应该是false