Problem:

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.

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.

哈哈,这题也没有参考别人的代码,我是看完了以上题目,修改了七次终于通过了。

我根据requirements for atoi写,

先写了个子函数,用来返回正确的数字字符串

在这当中首先是读过前面的空格,如果第一个非空格字符不是 + - 或者数字,那么返回空字符串。如果是+号或者-号,那么后边必须紧跟数字,否则也返回空字符。如果以上都没有返回,那么就是遇到数字了,直接读到非数字部分,然后将正负号与数字一同返回字符串。

再在atoi中判断返回的字符串

我定义的是long long 型来存,通过string转换为数字long long 型(通过包含sstream头文件,利用stringstream转的),然后判断long long 型在正负情况下和INT_MAX 或 INT_MIN 的比值,特别要注意是符号的时候,如果边界不对那么很多case通过不了,我一开始用long型发现不行,才转用long long 型的。

还有就是一开始我不知道原来一定要规定开头才算。如果数字在中间,前后其他字符就不算了。例如“abc123”虽然有123,但是因为开头的不是符合要求所以就不能返回数字,直接返回0即可。

class Solution {
public:
int atoi(const char *str)
{
string s = substringInteger(str);
if (s.size() == )
return ;
int positive = ;
if (s[] == '+')
s = s.substr(,s.size() - );
else if(s[] == '-')
{
s = s.substr(,s.size() - );
positive = ;
} std::stringstream ss;
ss<<s;
long long result;
ss>>result;
if (positive == )
{
long long maxval = ; // 这里直接用数字是因为我用 INT_MAX + 1 的时候显示的是 INT_MIN的值, -1的case会出错
if (result < maxval)
return -*result;
else
return INT_MIN;
}
else
{
if (result < INT_MAX)
return result;
else
return INT_MAX;
}
} private:
//leetcode7 return the sub string include interger
string substringInteger(string s)
{
if (s.size() == )
return "";
string substring;
int pos = -, len = ;
int index = ;
int positive = ;
while(s[index] == ' ' && index < s.size())
{
index++;
}
if (index == s.size())
return ""; if(s[index]!='+' && s[index]!='-' && !isdigit(s[index]))
return "";
if(s[index] == '+'&&index+<s.size())
if(!isdigit(s[index+]))
return "";
if(s[index] == '-'&&index+<s.size())
{
if(!isdigit(s[index+]))
return "";
else
positive = ;
} // detect till digit if exist
while(!isdigit(s[index])&&index<s.size())
{
index++;
}
if(index == s.size())
return "";
// find the length of the digit
pos = index;
while(isdigit(s[index])&&index<s.size())
{
index++;
}
len = index - pos;
substring = s.substr(pos,len);
// if negative return '-' in front
if (positive == )
substring = "-" + substring;
return substring;
}
};

这次coding中回顾并学习了 substr,sstream 中 stringstream 将string和任意型转换 INT_MAX 和 INT_MIN 特别边界处理时注意,因为有个尾数是8,还有就是代码中用中文注释的地方也要注意。

leetcode第八题--String to Integer (atoi)的更多相关文章

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

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

  2. [leetcode]经典算法题- String to Integer (atoi)

    题目描述: 把字符串转化为整数值 原文描述: Implement atoi to convert a string to an integer. Hint: Carefully consider al ...

  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(8)String to Integer (atoi)

    题目: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input ca ...

  5. 【leetcode❤python】 8. String to Integer (atoi)

    #-*- coding: UTF-8 -*-#需要考虑多种情况#以下几种是可以返回的数值#1.以0开头的字符串,如01201215#2.以正负号开头的字符串,如'+121215':'-1215489' ...

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

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

  7. Leetcode 8. String to Integer (atoi)(模拟题,水)

    8. String to Integer (atoi) Medium Implement atoi which converts a string to an integer. The functio ...

  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. 乘风破浪:LeetCode真题_008_String to Integer (atoi)

    乘风破浪:LeetCode真题_008_String to Integer (atoi) 一.前言 将整型转换成字符串,或者将字符串转换成整型,是经常出现的,也是必要的,因此我们需要熟练的掌握,当然也 ...

随机推荐

  1. NHibernate框架魅力美

    Nhibernate属于ORM框架之中的一个,在了解NHibernate之前我们先来了解什么是ORM? ORM框架是为了将类对象和关系建立映射.事实上说白了,就是通过一个 Mapping将我们的实体类 ...

  2. Android:创建耐磨应用 - 定义自己的布局

    创建自己的自定义布局(Creating Custom Layouts) 本文介绍如何创建自己的自定义通知和使用可穿戴UI库来创建自己的自定义布局同时你还需要知道耐磨设计标准(Wear Design P ...

  3. GRUB三步通(转)

    GRUB三步通 ################### GRUB的优点 ################### GRUB 是引导装入器(boot loader) -- 它负责装入内核并引导 Linux ...

  4. 【MongoDB】在windows平台mongodb切片集群(三)

    在过去的两年我们博客详细阐述了零碎工作集群和打造过程.在这篇博客中,我们主要分析测试结果一起支离破碎集群. 首先来看看碎片集群的每个状态.你可以看出来复制集A和B都是正常的: 一.开启分片集合 开启一 ...

  5. MVC 快速开发框架

    ASP.NET MVC 快速开发框架之 SqlSugar+SyntacticSugar+JQWidgetsSugar+jqwidgets jqwidgets.js: 是一个功能完整的框架,它具有专业的 ...

  6. ZOJ1610_Count the Colors(段树/为段更新)

    解决报告 意甲冠军: 一定长度8000段染.寻求染色完成后,.. 思路: 区间问题用线段树.成段的更新区间.最后把全部的区间下压到叶子结点,统计叶子结点的颜色. #include <iostre ...

  7. 数字使用相应的加密策略传递一个字符串后Java实现代码

    公司采用公用电话传递数据,数据小于8整数位,为了确保安全,     在转移的过程中需要加密,加密规则如下面的:         第一个数据下降,附图然后各加5,和除以10的余数取代该数字,       ...

  8. 必要的软件架构师——编译原理&#183;语法

    最近软测试.我观看进程的视频! 发现里面有很多内容已经在自我不错的接触过程.而占80%比例! 但其中的一部分.我很奇怪的一部分.研究,在这里,将我研究的内容整理分享给大家! 编译原理: 首先,我第一眼 ...

  9. 于 jsp第横梁list数据

            往往我们都会将查询到的数据显示到界面中,那么该怎样在界面显示.请看以下的具体解释:     0)前提得在jsp页面中获取后台传过来的数据(在此为List集合):             ...

  10. Entity Framework 6.1

    Entity Framework 6.1-Code First Code First-代码优先,先创建好领域模型.根据... 2014-04-21 14:56 阅读(6858) 评论(0)   Ent ...