Chinaunix首页 | 论坛 | 博客

AAA

  • 博客访问: 18415
  • 博文数量: 33
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 330
  • 用 户 组: 普通用户
  • 注册时间: 2015-04-17 08:23
个人简介

好记性不如烂笔头,记录学习历程和随想云云,欢迎各位大虾拍砖

文章分类

全部博文(33)

文章存档

2015年(33)

我的朋友
最近访客

分类: C/C++

2015-05-07 23:18:05

【问题描述】

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.


【解决方案】

点击(此处)折叠或打开

  1. int myAtoi(char *str) {
  2.     int sign = 1, base = 0, i = 0;
  3.     while (str[i] == ' ') { i++; }
  4.     if (str[i] == '-' || str[i] == '+') {
  5.         sign = 1 - 2 * (str[i++] == '-');
  6.     }
  7.     while (str[i] >= '0' && str[i] <= '9') {
  8.         if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
  9.             if (sign == 1) return INT_MAX;
  10.             else return INT_MIN;
  11.         }
  12.         base = 10 * base + (str[i++] - '0');
  13.     }
  14.     return base * sign;
  15. }

阅读(335) | 评论(0) | 转发(0) |
0

上一篇:Valid Sudoku

下一篇:Implement strStr()

给主人留下些什么吧!~~