LeetCode: 7-integer inversion

7. Integer inversion

Given a 32-bit signed integer, you need to invert the digits on each of the integers.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:

Assuming that our environment can only store 32-bit signed integers, the value range is [−231, 231 − 1]. According to this assumption, if the integer overflows after the inversion, it returns 0.

Problem-solving ideas

123--->321
右边依次取出每一位,做如下运算
0*10+3 = 3
3*10+2=32
32*10+1=321

-123--->321
先转换成正数处理
0*10+3=3
3*10+2=32
32*10+1=321 
--->-321

120--->21
0*10+0=0
0+10+2=2
2+10+1=21

根据上面的规律:
从0开始  0*10+从右往左取出每一位,直到给的这个数等于0了,说明这个数已经没有可以取处的值的。

还有一点需要注意的是:[−231,  231 − 1]使用int是存不下的,需要转成long类型

Code

class Solution {
    
    
public int reverse(int x) {
    
    
    long  sum = 0;
    long  temp = 0;
    //负数转成正数处理
    if(x < 0){
    
    
      temp = -1*x;
    }
    //正数直接使用
    temp = x;

	//还有值可取
    while(temp!=0 ){
    
    
        long i = temp % 10;
        temp = temp/10;
        sum = sum *10+i;
    }
    //在范围内
    if(sum > 0 && sum< 2147483647){
    
    
        return (int)sum;
    }
     //在范围内
    if( sum < 0 && sum > -2147483648){
    
    
        return (int)sum;
    }
    //不在范围内
    return 0;
    
    }
}

test

Insert picture description here

Guess you like

Origin blog.csdn.net/JAYU_37/article/details/107217002