leetcode problem 8: String to Integer (atoi)

Posted nosaferyao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode problem 8: String to Integer (atoi)相关的知识,希望对你有一定的参考价值。

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)的主要内容,如果未能解决你的问题,请参考以下文章

first-unique-character-in-a-string

leetcode problem 8: String to Integer (atoi)

#Leetcode# 387. First Unique Character in a String

LeetCode387. First Unique Character in a String

[数学] leetcode 8 String to Integer (atoi)

LeetCode 0387. 字符串中的第一个唯一字符