码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode problem 8: String to Integer (atoi)

时间:2017-11-18 21:53:45      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:integer   int   +=   str   index   public   while   ret   tco   

class Solution {
public:
    int myAtoi(string str) {
        int index = -1;
        int result = 0;
        int base = 10;
        int ssize = str.size();
        bool negtive = false;
        while (++index < ssize && (str[index] == ‘ ‘));
        if (index < ssize){
            if (str[index] == ‘+‘)
            {
                ++index;
            }
            else if (str[index] == ‘-‘)
            {
                negtive = true; ++index;
            }
        }
        if (index < ssize && str[index] == ‘0‘){
            ++index;
            if (index < ssize && (str[index] == ‘X‘ || str[index] == ‘x‘)){
                base = 16;
                ++index;
            }
        }
        while (index < ssize){
            char c = str[index];
            int v = 0;
            if (base == 10){
                if (c >= ‘0‘ && c <= ‘9‘){
                    v = c - ‘0‘;
                }
                                else {
                    break;
                }
            }
            else if (base == 16){
                if (c >= ‘0‘ && c <= ‘9‘){
                    v = c - ‘0‘;
                }
                else if (c >= ‘a‘ && c <= ‘f‘){
                     v = 10 + c - ‘a‘;
                }
                else if (c >= ‘A‘ && c <= ‘F‘){
                     v = 10 + c - ‘A‘;
                }
                else {
                    break;
                }
            }
            if (negtive){
                if ((INT_MIN + v)/base > (result)){
                    result = INT_MIN;
                    break;
                }
                else {
                    result *= base;
                    result -= v;
                }
            }
            else {
                if ((INT_MAX - v)/base < (result)){
                    result = INT_MAX;
                    break;
                }
                else {
                    result *= base;
                    result += v;
                }
            }
            index ++;
        }
        return result;
    }
};

  

leetcode problem 8: String to Integer (atoi)

标签:integer   int   +=   str   index   public   while   ret   tco   

原文地址:http://www.cnblogs.com/nosaferyao/p/7857940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!