[Daily] integer flip a problem

Reverse integer

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-bit signed integer, then the value range of [-231 231--1]. Please According to this hypothesis, if integer overflow after reverse it returns 0.

1, the string flipping
the x into a string, the string to integer inverted, and then returns.

class Solution {
public:
	int reverse(int x) {
		if (x == INT_MIN) {
			return 0;
		}
		if (x < 0) {
			return -reverse(-x);
		}
		long res = 0;
		string str = std::to_string(x);
		string res_str;
		for (int i = str.size() - 1; i >= 0; --i) {
			res_str.push_back(str[i]);
		}
		res = std::atoi(res_str.c_str());
		if (res > INT_MAX) {
			return 0;
		}
		return res;
	}
};

2, mathematical methods
take a position, and then to res * 10 + bits.

class Solution {
public:
    int reverse(int x) {
        if (x == INT_MIN) {
        	return 0;
        }
        if (x < 0) {
        	return -reverse(-x);
        }

        long res = 0;
        while (x > 0) {
        	int e = x % 10;
        	x /= 10;
        	res = res * 10 + e;
        }
        if (res > INT_MAX) {
        	return 0;
        }

        return res;
    }
};

// 下面是评论中的方法
int reverse(int x)
{
    int max = 0x7fffffff, min = 0x80000000;//int的最大值最小值
    long rs = 0;//用long类型判断溢出
    for(;x;rs = rs*10+x%10,x/=10);//逆序,正负通吃,不用单独考虑负值
    return rs>max||rs<min?0:rs;//超了最大值低于最小值就返回0
}
Published 73 original articles · won praise 90 · views 40000 +

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/105280323