leetcode - String to Integer (atoi)
2013-12-16 20:46 张汉生 阅读(167) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 int atoi(const char *str) { 4 while (*str==' ') 5 str++; 6 int sign = 1; 7 if (*str=='+') 8 str++; 9 else if (*str=='-'){ 10 str++; 11 sign = -1; 12 } 13 unsigned rlt=0; 14 unsigned maxL = INT_MAX; 15 if (sign==-1) 16 maxL += 1; 17 while (*str<='9' && *str>='0'){ 18 unsigned int off = *str-'0'; 19 unsigned int t = maxL - off; 20 if (t/10 < rlt){ 21 if (sign==1) 22 return INT_MAX; 23 return INT_MIN; 24 } 25 rlt = rlt * 10 + off; 26 str++; 27 } 28 if (sign==1) 29 return rlt; 30 return (-1) * rlt; 31 } 32 };