这道题在LeetCode OJ上难道属于Easy。可是通过率却比較低,究其原因是须要考虑的情况比較低,非常少有人一遍过吧。

【题目】

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.

【解析】

我预计没有多少人不看以下的要求就通过的吧!

这道题要求的 atoi 跟C++实现的不一样吧。比方我以为不符合要求的返回-1,而这道题要求返回0。

所以,有必要解释一下题目的要求:

1. 首先须要丢弃字符串前面的空格;

2. 然后可能有正负号(注意仅仅取一个,假设有多个正负号。那么说这个字符串是无法转换的,返回0。比方測试用例里就有个“+-2”);

3. 字符串能够包括0~9以外的字符,假设遇到非数字字符,那么仅仅取该字符之前的部分,如“-00123a66”返回为“-123”;

4. 假设超出int的范围,返回边界值(2147483647或-2147483648)。

综上,要求还是有点怪的,不看要求是非常难写对的,看了也不一定理解的对。

【Java代码】

public class Solution {
public int atoi(String str) { // 1. null or empty string
if (str == null || str.length() == 0) return 0; // 2. whitespaces
str = str.trim(); // 3. +/- sign
boolean positive = true;
int i = 0;
if (str.charAt(0) == '+') {
i++;
} else if (str.charAt(0) == '-') {
positive = false;
i++;
} // 4. calculate real value
double tmp = 0;
for ( ; i < str.length(); i++) {
int digit = str.charAt(i) - '0'; if (digit < 0 || digit > 9) break; // 5. handle min & max
if (positive) {
tmp = 10*tmp + digit;
if (tmp > Integer.MAX_VALUE) return Integer.MAX_VALUE;
} else {
tmp = 10*tmp - digit;
if (tmp < Integer.MIN_VALUE) return Integer.MIN_VALUE;
}
} int ret = (int)tmp;
return ret;
}
}

參考 http://www.programcreek.com/2012/12/leetcode-string-to-integer-atoi/ ,代码例如以下:

public int atoi(String str) {
if (str == null || str.length() < 1)
return 0; // trim white spaces
str = str.trim(); char flag = '+'; // check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
double result = 0; // calculate value
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + (str.charAt(i) - '0');
i++;
} if (flag == '-')
result = -result; // handle max and min
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE; if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE; return (int) result;
}

代码看起来更简洁,可是第一种写法能够及时跳出循环。不用计算完了再推断是否越界。

【LeetCode】String to Integer (atoi) 解题报告的更多相关文章

  1. LeetCode: String to Integer (atoi) 解题报告

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

  2. 【LeetCode】397. Integer Replacement 解题报告(Python)

    [LeetCode]397. Integer Replacement 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/inte ...

  3. [LeetCode] String to Integer (atoi) 字符串转为整数

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

  4. [Leetcode] String to integer atoi 字符串转换成整数

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

  5. [LeetCode] String to Integer (atoi) 字符串

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

  6. 【LeetCode】343. Integer Break 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 数学解法 动态规划 日期 题目地址:https:// ...

  7. [Leetcode]String to Integer (atoi) 简易实现方法

    刚看到题就想用数组做,发现大多数解也是用数组做的,突然看到一个清新脱俗的解法: int atoi(const char *str) { ; int n; string s(str); istrings ...

  8. [LeetCode]String to Integer (atoi)

    题意:字符串转正数 原题来自:https://leetcode.com/problems/string-to-integer-atoi/ 分析: <程序员面试宝典>上出现的面试题,主要是考 ...

  9. leetcode String to Integer (atoi) python

    class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int "& ...

随机推荐

  1. 支持辉光效果的Label

    支持辉光效果的Label 效果 源码 https://github.com/YouXianMing/UI-Component-Collection 中的 FBGlowLabel // // FBGlo ...

  2. Notification详解(含工具类)

                                                                     昨天一天只写了两篇文章,效率超低.追其原因呢,其实我一直在研究noti ...

  3. 多线程-Executors和Executor,线程池

    jdk1.5之前,所有的线程都是需要自己手动创建的,由jvm销毁,当请求过多的时候,频繁的创建和销毁线程是非常浪费资源的.jdk1.5为此做了优化,提供了 java.util.concurrent 包 ...

  4. YAML文件简介

    编程免不了要写配置文件,怎么写配置也是一门学问. YAML 是专门用来写配置文件的语言,非常简洁和强大,远比 JSON 格式方便. 本文介绍 YAML 的语法,以 JS-YAML 的实现为例.你可以去 ...

  5. 洛谷 P1138 第k小整数

    题目描述 现有n个正整数,n≤10000,要求出这n个正整数中的第k个最小整数(相同大小的整数只计算一次),k≤1000,正整数均小于30000. 输入输出格式 输入格式: 第一行为n和k; 第二行开 ...

  6. 京东的Netty实践,京麦TCP网关长连接容器架构

    背景 早期京麦搭建 HTTP 和 TCP 长连接功能主要用于消息通知的推送,并未应用于 API 网关.随着逐步对 NIO 的深入学习和对 Netty 框架的了解,以及对系统通信稳定能力越来越高的要求, ...

  7. go语言之进阶篇创建goroutine协程

    1.goroutine是什么 goroutine是Go并行设计的核心.goroutine说到底其实就是协程,但是它比线程更小,十几个goroutine可能体现在底层就是五六个线程,Go语言内部帮你实现 ...

  8. Solr调研总结(转)

    Solr调研总结 开发类型 全文检索相关开发 Solr版本 4.2 文件内容 本文介绍solr的功能使用及相关注意事项;主要包括以下内容:环境搭建及调试.两个核心配置文件介绍.中文分词器配置.维护索引 ...

  9. ZMQ和MessagePack的简单使用(转)

    近段日子在做一个比较复杂的项目,其中用到了开源软件ZMQ和MessagePack.ZMQ对底层网络通信进行了封装,是一个消息处理队列库, 使用起来非常方便.MessagePack是一个基于二进制的对象 ...

  10. COCO数据集深入理解

    TensorExpand/TensorExpand/Object detection/Data_interface/MSCOCO/ 深度学习数据集介绍及相互转换 Object segmentation ...