leetcode_2. integer reversal

  • Integer reverse : given a 32-bit signed integer, you need this integer numbers on each inverted.
示例1:

输入: 123
输出: 321

示例2:

输入: -123
输出: -321

示例3:

输入: 120
输出: 21

注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31,  2^31 − 1]。
请根据这个假设,如果反转后整数溢出那么就返回 0。
  • I wrote two hours, probably written out, but write more complicated, I think here absorbed a clearer idea, and it had to be improved.
  • The core here is to advance to rt y type of test double if overflow, returns 0, otherwise assigned to rt. Which reversed the numbers of every stored in an array.
  • When execution: 4 ms, beat all C submission of 90.78% of user
    memory consumption: 6.7 MB, defeated 85.35% of all users in C submission
  • Evaluated on the max and min used herein bitwise.
int reverse(int x) {
    int tmp[10]={0},i,j;
    int rt=0;
    double y=0;   //这里因为int型的rt计算后可能整型溢出报错,用y来检测是否溢出
    int max=~(unsigned int)0/2;   //2147483647
    int min=~(unsigned int)0/2+1; //-2147483648
    for (i = 0; i < 10 && x != 0; i++)  //这里的x!=0很重要
    {
        tmp[i] = x % 10;  //tmp存储了x的每一位
        x = x / 10;
    }
    for (j = 0; j < i;j++) //i=10
    {
        y= 10 * y + tmp[j];
        if(y>max||y<min)
            return 0;
        else
            rt = y;
    }
return rt;
}

  • Another one of the following example, I think is not bad:
Published 77 original articles · won praise 19 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42932834/article/details/95189320