Reverse number - Algorithm

Number of reversal

Problem Description

Gives a 32-bit signed integer, you need this integer number on each inverted.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:

Suppose we have an environment can store the 32 位symbols are integer, its value is in the range of [ 2 31 −2^{31} , 2 31 1 2^{31} − 1 ]. Please According to this hypothesis, if integer overflow after reverse it returns 0.

problem analysis

Here you should consider the possibility of data overflow, overflow for this data if it returns 0, select the appropriate data type is an important issue.

Code

class Solution {
public:
    int reverse(int x) {
        if(x/10 == 0) return x; //一般个位情况,不需要反转,原样输出
        int y = 0;
        while(x) {
            if(y > INT_MAX/10 || y < INT_MIN/10) //数据溢出
                return 0;
            y *= 10;
            y += x%10; //取出x的个位,存入y中相应的位置
            x /= 10;   //去掉x的个位
        }
        return y;
    }
};

operation result

输入

123

输出

321

to sum up

The Inversion of using the original number by one from the end of the split, the first number from the new splicing. Data overflow control using intupper and lower limits of the type - INT_MAXand INT_MINcontrolled.

Because intoccupies 4 bytes 32-bit, binary-coded according to the rule

INT_MAX = 2 31 2^{31} -1

INT_MIN = - 2 31 2^{31}

C / C ++, all exceeds the limit, there will be an overflow occurs warning, but does not appear error.

注意:有符号(signed)数最高位为符号位,在无溢出(overflow、underflow)的情况下,其符号位不变,符号也就不变。

发布了59 篇原创文章 · 获赞 5 · 访问量 5054

Guess you like

Origin blog.csdn.net/qq_38496329/article/details/104084554