7_Reverse Integer

7.Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

没有想出来, 仿照(或者照搬?)http://www.cnblogs.com/grandyang/p/4125588.html来写

注意点:
反转溢出问题, 解决方法: 使用比该数字范围大的类型定义返回值

版本一: 拆分每个位的思想是我的, 其他细节参考上述博客

class Solution {
public:
    int reverse(int x) {
        long long res = 0;
        vector<int> bit;
        
        while (0 != x) {
            bit.push_back(x % 10);
            x /= 10;
        }
        
        for (int i = 0; i < bit.size(); i++) {
            res =res * 10 + bit[i];
        }
        
        return (res < INT_MIN || res > INT_MAX) ? 0 : res;
    }
};

版本二: 半个自己写的, 考虑符号, 虽然多余了

class Solution {
public:
    int reverse(int x) {
		long long ret = 0;
		// int positive = 1;
		long long positive = 1;

		if (x < 0) {
			positive = -1;
			x *= positive;
		}

		while (x != 0) {
			ret = ret * 10 + x % 10;
			x /= 10;
		}
        
        ret *= positive;
		
		return (ret < INT_MIN || ret > INT_MAX) ? 0 : ret;
    }
};
class Solution {
public:
    int reverse(int x) {
        long long int ret = 0;
        
        while(0 != x) {
            ret = ret*10 + x%10;
            x /= 10;
        }
        
        //return (ret > INT_MIN || ret < INT_MAX)? ret : 0;
         return (ret < INT_MIN || ret > INT_MAX) ? 0 : ret;
    }
};
posted @ 2019-02-18 20:32  张飘扬  阅读(121)  评论(0编辑  收藏  举报