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

String to Integer (atoi)

时间:2015-04-21 00:12:11      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:

String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

边界条件太多,题目也没i说清楚,都是根据测试数据修改程序……也算过了

Runtime: 15 ms

 

#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;

class Solution {
public:
    int myAtoi(string str) {
        double num = 0;
        bool isPositive = true;
        if (str=="")
            return 0;
        int i = 0;
        while (str[i] ==  )
            i++;
        if (str[i] == -){
            isPositive = false;
            i++;
            if (str[i] == +||str[i]==-){
                return 0;
            }
        }
        if (str[i] == +){
            i++;
            if (str[i] == + || str[i] == -){
                return 0;
            }
        }
    
        while (i <str.length()&&str[i]>=0&&str[i]<=9){
            num = num * 10 + (str[i]-0);
            i++;
        }
        if (isPositive == false){
            num = num*-1;
        }
        if (num > INT_MAX)
            return INT_MAX;
        else if (num < INT_MIN)
            return INT_MIN;
        else
            return num;
    }
};

int main(){
    Solution solution;
    printf("%d", solution.myAtoi("    -123"));
    system("pause");
}

 

String to Integer (atoi)

标签:

原文地址:http://www.cnblogs.com/JeromeHuang/p/4442993.html

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