[LeetCode]007. Reverse Integer

发布时间:2014-10-22 14:30:18编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"[LeetCode]007. Reverse Integer",主要涉及到[LeetCode]007. Reverse Integer方面的内容,对于[LeetCode]007. 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). Solution: use the math method to reverse the order,  result = result*10 + left; the + operation in the while loop can eliminate the redundant 0; such as “500--->5 (which is '0+0+5')"; use the Math.abs() method to get the abstract value, because the module on negative number has ambiguity.(different languages have different results). 负数取模有争议,不同的编程语言给出的结果不同,参见 http://ceeji.net/blog/mod-in-real/ 实数范围内的求模(求余)运算:负数求余究竟怎么求 java里表示整数最大值Integer.MAX_VALUE  (2^31 -1); public class Solution { public int reverse(int x) { // Start typing your Java solution below // DO NOT write main() function int flag = 1; if(x<0){ flag = -1; } int temp = Math.abs(x); int left = 0; int result = 0; while(temp != 0){ left = temp % 10; result = result*10 + left; temp = temp/10; } if(result > Integer.MAX_VALUE){ return -1; // only return -1 here, or we can print one message //or use a static field variable "isValid" for representint states? }else{ return result*flag; } } }

上一篇:HTML5 App实战(7):连连看