LeetCode - String To Integer
Consider very carefully to cover all the possible input conditions!
atoi: string -> integer
input: str
1. size:
different C++ data type's size in different machine [list]: http://hi.baidu.com/yangyangye2008/item/ba0a35395420d2f9df222157
(default: int - 4 bytes)
2. begin (' ','+','-') , others' error
3. inside('0'-'9', ' '), others' error
4. attention to the return type: int
but set the string-num type "long long" first, then judge it.
* if string-num's size is bigger than the int-type size, then return the biggest int(positive/negtive):
if(negtive)
{
ret = ret<=0x80000000 ? ~(unsigned int)ret+1 : 0x80000000;
}
else
{
ret = ret<=0x7FFFFFFF ? ret : 0x7FFFFFFF;
}
5. integer: aN = ((((a1*10+a2)*10+...)*10...)+an-1)*10+an;
attach code:
class Solution { public: int atoi(const char *str) { // Start typing your C/C++ solution below // DO NOT write int main() function long long ret = 0; int i = 0; bool negtive = false; while(str[i] == ' ') i++; if(str[i]=='+') i++; else if(str[i]=='-') {negtive=true;i++;} while(str[i]!='\0' && str[i]>='0' && str[i]<='9') { int d = str[i]-'0'; ret = 10*ret+d; i++; } if(negtive) { ret = ret<=0x80000000 ? ~(unsigned int)ret+1 : 0x80000000; } else { ret = ret<=0x7FFFFFFF ? ret : 0x7FFFFFFF; } return ret; } };
posted on 2013-04-13 22:23 highstar88 阅读(128) 评论(0) 编辑 收藏 举报