[LeetCode] Reverse Integer

来源:互联网 发布:ubuntu怎么新建文件夹 编辑:程序博客网 时间:2024/06/07 02:45

题目要求: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).


Java代码:

public class Solution {
    public int reverse(int x) {
        int sum=0;
        while(x!=0){
            int temp=x%10;
            sum = sum*10+temp;
            x=x/10;
        }
        return sum;
    }
}

确实通过了 但是没有考虑上面提到的特殊情况和边界值的问题,在网上找到了一个这样的例子:

  1. class Solution {  
  2. public:  
  3.     int reverse(int x) {  
  4.         // IMPORTANT: Please reset any member data you declared, as  
  5.         // the same Solution instance will be reused for each test case.  
  6.           
  7.         const int max = 0x7fffffff;  //int最大值  
  8.         const int min = 0x80000000;  //int最小值  
  9.         long long sum = 0;   
  10.           
  11.         while(x != 0)  
  12.         {  
  13.             int temp = x % 10;  
  14.             sum = sum * 10 + temp;  
  15.             if (sum > max || sum < min)   //溢出处理  
  16.             {  
  17.                 sum = sum > 0 ? max : min;    
  18.                 return sum;  
  19.             }  
  20.             x = x / 10;  
  21.         }  
  22.         return sum;  
  23.     }  
  24. };  
这段代码考虑了边界值的问题。

0 0
原创粉丝点击