LeetCode 8


### Description:

Implement atoi to convert a string to an integer.

  • 题意:
    将字符串转换成integer

  • 思路:
    这个字符串的组成是, x个空格(x可为0) + 一个正负号(或者没有) + 加数字字符串, 中间若出现不是数字的字符,则计算之前的字符串, 所以只要考虑边界就可以了, 具体看代码


Example:


  1. Input: " -1"
    Output: -1

  2. Input: " -12ab34"
    Output: -12



代码


C

int myAtoi(char* str){
    int isf;
    int i=0;
    long long res=0;
    int l = strlen(str);
    if(str == NULL){
        return 0;
    }
    while(str[i] == ' '){
        i++;
    }
    isf = str[i] == '-' ? -1: 1;
    if(str[i] == '-' || str[i] == '+')
        i++;

    while(str[i]>='0' && str[i]<='9' && i < l){
        res = res*10 + str[i] - '0';
        if(res*isf > INT_MAX){
            return INT_MAX;
        }
        else if(res*isf < INT_MIN){
            return INT_MIN;
        }
        i++;
    }
    return (int)(res*isf);
}

posted @ 2018-03-14 16:43  shengwudiyi  阅读(77)  评论(0编辑  收藏  举报