• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: String to Integer (atoi)

这种题就是考你考虑了多少些情况,第一次没有考虑到的情况有:+-号,超出int范围,多数次过

 1 class Solution {
 2 public:
 3     int atoi(const char *str) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         bool showed = false;
 7         int s = 0;
 8         bool negtive = false;
 9         for (int i = 0; *(str+i) != '\0'; i++) {
10             if (!showed) {
11                 if (*(str+i) == ' ') continue;
12                 if (*(str+i) >= '0' && *(str+i) <= '9') {
13                     showed = true;
14                     s = (int)(*(str+i) - '0');
15                 }
16                 else if (*(str+i) == '-') {
17                     showed = true;
18                     negtive = true;
19                 }
20                 else if (*(str+i) == '+') showed = true;
21                 else return 0;
22             }
23             else {
24                 if (*(str+i) == ' ') return negtive? -s : s;
25                 if (*(str+i) >= '0' && *(str+i) <= '9') {
26                     if (s > (INT_MAX - (int)(*(str+i)-'0'))/10)
27                         return negtive? INT_MIN : INT_MAX;
28                     s = s*10 + (int)(*(str+i) - '0');
29                 }
30                 else return negtive? -s : s;
31             }
32         }
33         return negtive? -s : s;
34     }
35 };

 后来写了个更加精简的代码

 1 class Solution {
 2 public:
 3     int atoi(const char *str) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         while (isspace(*str)) str++;
 7         int ret = 0;
 8         bool isNeg = false;
 9         if (*str == '+') str++;
10         if (*str == '-') {
11             isNeg = !isNeg;
12             str++;
13         }
14         while (isdigit(*str)) {
15             if (ret > (INT_MAX - int(*str-'0'))/10) return isNeg? INT_MIN : INT_MAX;
16             ret = ret*10+int(*str-'0');
17             str++;
18         }
19         return isNeg? -ret : ret;
20     }
21 };

 

 

posted @ 2013-04-21 10:43  ying_vincent  阅读(158)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3