leetcode小白解题记录——第七题

来源:互联网 发布:医疗答题软件 编辑:程序博客网 时间:2024/05/12 06:29

7. Reverse Integer

 
 My Submissions
  • Total Accepted: 165524
  • Total Submissions: 696092
  • Difficulty: Easy

Reverse digits of an integer.

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

click to show spoilers.

这个问题也比较直观,关键是一个考虑运算的时候有可能出现溢出问题,对于溢出问题,有如下的解决方案:

1.

class Solution {public:    int reverse(int x) {        double s=0;//一定要设置成double,否则 下面while循环里 s = s * 10 + x % 10; s每次都乘以10,可能会导致整数溢出        int flag=1;        if(x==0) return 0;        if(x<0)         {            flag=-1;            x=x*(-1);        }        while(x>0){            s = s * 10 + x % 10;            x=x/10;        }        s=s*flag;        return (s > INT_MAX || s < INT_MIN? 0 : s);    }};
2. 在做乘10运算的时候先判断一下

  1. public class Solution {
  2.     public int reverse(int x) {
  3.         if (x == 0) return 0;
  4.         int res = 0;
  5.         int sign = 1;
  6.         if (x < 0) {
  7.             sign = -1;
  8.             x = -1 * x;
  9.         }
  10.         while (x != 0) {
  11.             if (res > (Integer.MAX_VALUE - x % 10) / 10) {
  12.                 return 0;
  13.             }
  14.             res = res * 10 + x % 10;
  15.             x = x / 10;
  16.         }
  17.         return res * sign;
  18.     }
  19. }


0 0