Monday, December 31, 2012

[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).
» Solve this problem

[解题思路]
如果是用字符串来逆序的话,需要考虑0的特殊性,但是如果直接用一个integer来滚动生成的话,0就不是问题了。
当然,溢出的问题是存在的,所以return -1。

[Code]
1:    int reverse(int x) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      int lastDigit = 0;  
5:      int result = 0;  
6:      bool isNeg = x>0? false:true;  
7:      x = abs(x);  
8:      while(x>0)  
9:      {  
10:        lastDigit = x%10;  
11:        result = result*10 + lastDigit;  
12:        x = x/10;  
13:      }  
14:      if(result<0) return -1;  
15:      if(isNeg)  
16:        result *=-1;  
17:      return result;      
18:    }  



Version 2, Refactor code, 3/5/2012
Rethink for a while. And actually, we don't need to use special logic to handle '+' and '-', because the sign can be kept during calculating. Only 8 lines can resolve this problem.
1:       int reverse(int x) {  
2:            int newN =0, left =0;  
3:            while(x != 0)  
4:            {  
5:                 left = x%10;  
6:                 newN = newN*10 + left;  
7:                 x = x/10;  
8:            }  
9:            return newN;  
10:       }  


No comments:

Post a Comment