Ritual Algorithm Mathematics Class - Integer Reversal

Table of contents

integer inversion

answer:

code:


integer inversion

7. Integer Reverse - LeetCode

7. Integer inversion

Given a 32-bit signed integer  x , return  x the result of inverting the numeric part of it.

[−231,  231 − 1] Returns 0 if the inverted integer exceeds the range of a 32-bit signed integer  .

Assume the environment does not allow storing 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
 Output: 321

Example 2:

Input: x = -123
 Output: -321

Example 3:

Input: x = 120
 Output: 21

Example 4:

Input: x = 0
 Output: 0

hint:

  • -231 <= x <= 231 - 1

题解:

如何反转整数
用栈?或者变成字符串,再去反转字符串?
这两种方式是可以,但并不好。实际上我们只要能拿到这个整数的 末尾数字 就可以了。
以12345为例,先拿到5,再拿到4,之后是3,2,1,我们按这样的顺序就可以反向拼接处一个数字了,也就能达到 反转 的效果。
怎么拿末尾数字呢?模除运算

The judgment condition of the cycle:

x>0? But this is wrong, because
the judgment condition of the negative number cycle should be while(x!=0), no matter positive or negative, according to the above continuous /10 operation, it will eventually become 0, so the judgment termination condition is !=0

Values ​​range from [−2^31,  2^31 − 1]

First 2^31=2147483648

So we judge whether the size overflows before storing the last bit in res

code:

class Solution {
    public int reverse(int x) {
        int res=0;
        while(x!=0){
            int temp=x%10;
            if(res>214748364||res==214748364&&temp>7){
                return 0;
            }
            if(res<-214748364||res==-214748364&&temp<-8){
                return 0;
            }
            res=res*10+temp;
            x/=10;
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/131670932