LeetCode 7 整数反转

LeetCode 7 整数反转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321
示例 2:

输入: -123
输出: -321
示例 3:

输入: 120
输出: 21

分析

不需要算法,所以直接玩杂技了。

C++代码

class Solution {
public:
    string reverse(string s){
        int len = s.length();
        for(int i = 0; i < len/2; i++){
            char c = s[i];
            s[i] = s[len-1-i];
            s[len-1-i] = c;
        }
        return s;
    }
    int reverse(int x) {
        bool nag;
        string tem;
        stringstream ss;
        
        ss << x;
        if(x < 0)
            nag = 1;
        else
            nag = 0;
        if(nag == 1){
            ss >> tem;
            tem = tem.substr(1,tem.length()-1);
            tem = reverse(tem);
            tem = "-" + tem;
        }
        else{
            ss >> tem;
            tem = reverse(tem);
        }
        long int res = stol(tem,0,10);
        if(res > INT_MAX || res < INT_MIN){
            res = 0;
        }
        return (int)res;
    }
    

};

你可能感兴趣的:(LeetCode)