leetcode 7. Reverse Integer \ 8. String to Integer (atoi)

来源:互联网 发布:java基础看不懂 编辑:程序博客网 时间:2024/06/16 16:31

  • Reverse Integer
  • String to Integer atoi

7. Reverse Integer

class Solution {public:    int reverse(int x) {        long long result = 0;        while(x != 0) {            result = result*10 + x%10;            x = x/10;            cout << x << " " << result << endl;        }        if(result > INT_MAX || result < INT_MIN)            result = 0;        return result;    }};

8. String to Integer (atoi)

class Solution {public:    int myAtoi(string str) {        int result = 0;        int str_len = str.length();        int stt = 0;        int sign = 1;        while(str[stt] == ' ')   stt++;        if(str[stt] == '+' || str[stt] == '-')             sign = (str[stt++] == '+')?1:-1;        while(str[stt] >= '0' && str[stt] <= '9') {            if (result >  INT_MAX / 10 || (result == INT_MAX / 10 && str[stt] - '0' > 7)) {                if (sign == 1) return INT_MAX;                else return INT_MIN;            }            result = result*10 + (str[stt++] - '0');        }        result *= sign;        return result;    }};
0 0