[leetcode:7] 字符串转整数的溢出判断

来源:互联网 发布:阿里云服务器安装镜像 编辑:程序博客网 时间:2024/05/21 18:47
#include<iostream>#include <fstream>#include<vector>#include<stdio.h>#include<stdlib.h>#include<errno.h>#include <algorithm>#include <functional>using namespace std;void empty(const char* fmt, ...) {}#define print emptyclass Solution {public:    char int_max[65];    char int_min[65];    Solution() {        snprintf(int_max, 65, "%d", INT_MAX);        snprintf(int_min, 65, "%d", INT_MIN);    }       bool overflow(const char* num) {        if (num[0] == '-') {            if (strlen(num) < strlen(int_min)) {                return false;            }               for (int i = 1; num[i]; ++i) {                if (num[i] < int_min[i]) {                    return false;                } else if (num[i] > int_min[i]) {                    return true;                }               }               return false;        } else {            if (strlen(num) < strlen(int_max)) {                return false;            }               for (int i = 0; num[i]; ++i) {                if (num[i] < int_max[i]) {                    return false;                } else if (num[i] > int_max[i]) {                    return true;                }               }               return false;        }       }       int reverse(int x) {        char buf[65];            char* p = buf;        snprintf(buf, 65, "%d", x);         bool neg = false;        if (buf[0] == '-') {            neg = true;            p = &buf[1];         }           string res(p);        std::reverse(res.begin(), res.end());        if (neg) {            string neg_str = "-";            neg_str += res;            if (overflow(neg_str.c_str())) return 0;            return atoi(neg_str.c_str());        } else {            if (overflow(res.c_str())) return 0;            return atoi(res.c_str());        }       }   };// Your NumArray object will be instantiated and called as such:int main(int,char*[]) {    Solution s; /*    ifstream infile("input");    istreambuf_iterator<char> beg(infile), end;    string a(beg, end);    infile.close();    a.erase(a.end() - 1);*/        cout << s.reverse(1534236469);    return 0;}

0 0
原创粉丝点击