题目

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.

spoilers alert... click to show requirements for atoi.

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.

代码

class Solution {
public:
int myAtoi(string str) {
const size_t len = str.length();
// index of str
size_t i = ;
// skip the white space
while ( str[i]==' ' && i<len ) i++;
int sign = ;
if ( str[i]=='+' ) {
sign = ;
++i;
}
else if( str[i]=='-' ){
sign = -;
++i;
}
// visit all the other char
int num = ;
while ( i < len )
{
// not numerical char
if ( str[i]<'' || str[i]>'' ) break;
// overflow max bound or min bound
if ( num > INT_MAX/ || ( num==INT_MAX/ && (str[i]-'')>INT_MAX%))
{
return sign== ? INT_MAX : INT_MIN;
}
// accumulate the num
num = num * + str[i] - '';
++i;
}
// return the result
return num * sign;
}
};

Tips

逐步把case处理掉。这里主要有两个点需要关注:

(1)

复习了一下字符串相减,就是其ASCII码相减,这个跟学C语言的时候差不多。

(2)

判断是否超出INT_MAX的时候,一开始写成了“num*10 > INT_MAX”,这种写法是有问题的比如下面的test case就无法通过:

"      -11919730356x"

在代码中加一句每次处理num前看看num是什么的语句cout << "num:" << num << ",num*10:" << num*10 <<endl;

num:0,num*10:0
num:1,num*10:10
num:11,num*10:110
num:119,num*10:1190
num:1191,num*10:11910
num:11919,num*10:119190
num:119197,num*10:1191970
num:1191973,num*10:11919730
num:11919730,num*10:119197300
num:119197303,num*10:1191973030
num:1191973035,num*10:-965171538

在这一步就出错了,原因是

2147483647(INT_MAX)

1191973035*10 超出了int类型的限制,就溢出了。

这里有一个问题,为什么溢出的值是-965171538呢?

首先11919730350由十进制转换为二进制是1011 0001100111 1000101001 1010101110 (总共34位数,不包括符号位)

根据题意要求返回的是int型(占4个byte,算第一个符号位在内一共32为);此时num的最高的两位(34 33)就被舍弃了,最终保留的结果是

num=11 0001100111 1000101001 1010101110

第一位是符号位1(代表负数),其余的31位转换成十进制的数就是96517538.

所以 还是用num > INT_MAX/10这种比较形式安全(保证num不会超过INT_MAX的限制),以后这种方法也可以沿用。

下面的blog是详细讲C语言整形溢出的。

http://coolshell.cn/articles/11466.html

=============================================

第二次过这道题,最关键的溢出判断的点考虑到了。一些细节,刷了两遍也AC了。

class Solution {
public:
int myAtoi(string str) {
const int len = str.size();
int i = ;
while ( str[i]==' ' && i<len ) ++i;
if ( i==len ) return ;
int sign = ;
if ( str[i]=='+' ){
sign = ;
++i;
}
else if ( str[i]=='-' ){
sign = -;
++i;
}
int num = ;
while ( i<len )
{
if ( str[i]<'' || str[i]>'' ) break;
if ( num>INT_MAX/ || ( num==INT_MAX/ && (str[i]-'')>INT_MAX% ) )
{
return sign== ? INT_MAX : INT_MIN;
}
num = *num + (str[i]-'');
++i;
}
return num * sign;
}
};

【String to Integer (atoi) 】cpp的更多相关文章

  1. 【leetcode】String to Integer (atoi)

    String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...

  2. 【Leet Code】String to Integer (atoi) ——常考类型题

    String to Integer (atoi) Total Accepted: 15482 Total Submissions: 106043My Submissions Implement ato ...

  3. LeetCode【8】. String to Integer (atoi) --java实现

    String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...

  4. 【LeetCode-面试算法经典-Java实现】【008-String to Integer (atoi) (字符串转成整数)】

    [008-String to Integer (atoi) (字符串转成整数)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Implement atoi to co ...

  5. String to Integer (atoi) - 字符串转为整形,atoi 函数(Java )

    String to Integer (atoi) Implement atoi to convert a string to an integer. [函数说明]atoi() 函数会扫描 str 字符 ...

  6. No.008 String to Integer (atoi)

    8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...

  7. leetcode第八题 String to Integer (atoi) (java)

    String to Integer (atoi) time=272ms   accepted 需考虑各种可能出现的情况 public class Solution { public int atoi( ...

  8. leetcode day6 -- String to Integer (atoi) &amp;&amp; Best Time to Buy and Sell Stock I II III

    1.  String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully con ...

  9. Kotlin实现LeetCode算法题之String to Integer (atoi)

    题目String to Integer (atoi)(难度Medium) 大意是找出给定字串开头部分的整型数值,忽略开头的空格,注意符号,对超出Integer的数做取边界值处理. 方案1 class ...

随机推荐

  1. CSS3中颜色线性渐变实战

    css3线性渐变可以设置3个参数值:方向.起始颜色.结束颜色.最简单的模式只需要定义起始颜色和结束颜色,起点.终点和方向默认自元素的顶部到底部.下面举例说明: CSS Code复制内容到剪贴板 .te ...

  2. WCF+EntityFramework+mysql总结

    用WCF+Ef操作Mysql数据库的,现在,写一下经验总结,希望对大家有帮助. 1.需下载并安装MySql Connector Net 6.5.4 2.在ef层和wcf服务层引用dll :Mysql. ...

  3. Vue.js学习 Item12 – 内部响应式原理探究

    深入响应式原理 大部分的基础内容我们已经讲到了,现在讲点底层内容.Vue.js 最显著的一个功能是响应系统 —— 模型只是普通对象,修改它则更新视图.这让状态管理非常简单且直观,不过理解它的原理也很重 ...

  4. 【转】IE11的变化

    1.navigator.userAgent中不再包含“MSIE”关键字 2.用javascript的判断是否是IE11的方法是: var isIE11 = (sUserAgent.toLowerCas ...

  5. 修改 WordPress 文件上传目录

    WordPress 默认的上传目录位于 wp-content/uploads ,并且根据设置还可以按照年月归档.但是如果要上传一个头像,或者幻灯片的话,也跟附件混在一起总是不太好吧?幸好 WordPr ...

  6. Vmware为Ubuntu安装VmTools

    From:http://www.cnblogs.com/killerlegend/p/3632443.html Author:KillerLegend 1:首先打开Vmware并运行里面的Ubuntu ...

  7. ViewPager中GridView问题

    GridView 嵌套在ViewPager中问题. 1. GridView属性设置无法显示. 正常显示方式 <GridView android:padding="8dip" ...

  8. div+css的优势在哪?

    1.符合W3C标准.微软等公司都是他的支持者. 2.所搜引擎更加友好. 3.样式调整更加方便. 4.css简洁的代码,减少了带宽. 5.表现和结构分离.在团队开发中更容易分工 并不是取代table,t ...

  9. C++primer 阅读点滴记录(一)

    第十三章 复制控制:(copy control) 复制构造函数(copy constructor) 复制操作符(assignment operator) ps: 什么时候需要显示的定义复制控制操作:类 ...

  10. 黑白棋游戏 (codevs 2743)题解

    [问题描述] 黑白棋游戏的棋盘由4×4方格阵列构成.棋盘的每一方格中放有1枚棋子,共有8枚白棋子和8枚黑棋子.这16枚棋子的每一种放置方案都构成一个游戏状态.在棋盘上拥有1条公共边的2个方格称为相邻方 ...