2016年2月20日 星期六

LEET code -- 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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.




規則:
一開始先移除空白
在判斷是+ 或是-
合法的是 +100 OR -100
不能有+++100   --100  +-100  -+100  這都不行
接著去判斷是不是數字
只會計算連續數字,如果遇到非數字就直接回傳

要注意13 14行  要先判斷  *10之前會不會爆掉(記得ans要乘上pos)

在判斷17 18行  加上去idx會不會爆掉(記得ans跟idx要乘上pos)




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int myAtoi(char* str) {
    int ans=0;
    int pos=1;
    while(*str && *str==' ')str++;//pass white space
    //while(*str && *str=='+'){str++;}//pass continue+        //however it is no need
    //while(*str && *str=='-'){str++;pos=-1;}//same above       //however it is no need
    if( *str=='-'){pos= -1;str++;}
    else if( *str=='+'){str++;}
    int idx=(int)*str-'0';
    str++;
    if(idx <0 || idx>9)return 0;//not a number
    while(idx>=0 && idx<=9){//can't put *str in here, the last number will pass
        if( pos==1 && (2147483647/10   <(ans*pos) )  )return 2147483647; //remember to multip the pos
        else if( pos==-1 && (-2147483648/10  > (ans*pos)  ) ){return -2147483648;}
        
        ans*=10;
        if( pos==1 && (2147483647 - ans*pos < idx)  )return 2147483647;
        else if( pos==-1 && (-2147483648 -ans*pos > idx*pos  ) )return -2147483648; //remember to add pos to both of ans and idx
        ans+=idx;
        if(!*str)break;
        idx=(int)*str-'0';
        str++;

    }

    return ans*pos;
}



沒有留言:

張貼留言