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

Solution

1. 用String s = str.trim();裁掉前面后面的空格。

2. 记录起始的+,-符号。

3. 用Long来转数字,这样的话就算越界也没什么了。

 public class Solution {
public int atoi(String str) {
if (str == null) {
return 0;
} // remove the spaces in the begining and the end.
String s = str.trim(); boolean minus = false;
long num = 0;
for (int i = 0; i < s.length(); i++) {
/*
takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
*/
if (i == 0 && s.charAt(i) == '+') {
continue;
} else if (i == 0 && s.charAt(i) == '-'){
// get the
minus = true;
continue;
} int c = s.charAt(i) - '0';
if (c > 9 || c < 0) {
// invalid character.
break;
} num = num * 10 + c;
} // If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is // returned.
if (minus) {
num = -num;
num = Math.max(num, Integer.MIN_VALUE);
} else {
num = Math.min(num, Integer.MAX_VALUE);
} return (int)num;
}
}

2015.1.3 redo,

leetcode升级了test case,加入了更大的比long还大的数。这样我们必须在循环里就判断是不是越界就退出了,否则long也会爆掉的。

 public class Solution {
public int atoi(String str) {
long ret = 0; // ___+1234__
// Delete the leading and tailing spaces.
String sNew = str.trim(); if (sNew.length() == 0) {
return 0;
} boolean positive = true;
for (int i = 0; i < sNew.length(); i++) {
char c = sNew.charAt(i);
if (i == 0 && c == '+') {
continue;
} else if (i == 0 && c == '-') {
positive = false;
continue;
} if (!(c <= '9' && c >= '0')) {
break;
} int dig = positive ? c - '0': '0' - c; ret = ret * 10 + dig; // bug 2: should consider the out of range.
if (ret > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (ret < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
} return (int)ret;
}
}

GitHub

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/Atoi.java

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

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

    这道题在LeetCode OJ上难道属于Easy.可是通过率却比較低,究其原因是须要考虑的情况比較低,非常少有人一遍过吧. [题目] Implement atoi to convert a strin ...

  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. 支持向量机-SVM 学习

    一 .支持向量机(SVM) 1.1 符号定义 标签 y 不再取 0 或 1,而是: y∈{-1, 1} 定义函数: 向量,没有第 0 个维度,b 为截距,预测函数定义为: 1.2 函数间隔与几何间隔 ...

  2. vim缩进参考线

    编辑缩进嵌套的文件时想找到对应的层级比较困难,写了一个函数,使用cc选项设定一条辅助线,标识到指定的缩进层级.代码如下: ? ReferenceLine 1 2 3 4 5 6 7 8 9 10 11 ...

  3. Redis学习之路(007)- Redis学习手册(实例代码)

    在之前的博客中已经非常详细的介绍了Redis的各种操作命令.运行机制和服务器初始化参数配置.本篇博客是该系列博客中的最后一篇,在这里将给出基于Redis客户端组件访问并操作Redis服务器的代码示例. ...

  4. 【C语言】练习2-8

     题目来源:<The C programming language>中的习题P38  练习2-1:  编写一个函数rightrot(x,n),该函数返回将x循环右移(即从最右端移除的位将从 ...

  5. OpenCV 学习笔记03 boundingRect、minAreaRect、minEnclosingCircle、boxPoints、int0、circle、rectangle函数的用法

    函数中的代码是部分代码,详细代码在最后 1 cv2.boundingRect 作用:矩形边框(boundingRect),用于计算图像一系列点的外部矩形边界. cv2.boundingRect(arr ...

  6. iOS UILabel设置居上对齐,居中对齐,居下对齐

    在iOS中默认的UILabel中的文字在竖直方向上仅仅能居中对齐,博主參考国外站点.从UILabel继承了一个新类,实现了居上对齐,居中对齐,居下对齐.详细例如以下: // //  myUILabel ...

  7. 具体解释Hibernate中cascade与inverse

    学习hibernate的时候对级联关系的概念老是分不清楚,尤其是cascade.inverse傻傻分不清.以下通过样例来简单说明. 准备工作: 首先创建数据库,新建两张表: 教室表classes (字 ...

  8. MPU6050陀螺仪和加速度计的校准

    加速度计和陀螺仪的校准: 在传感器静止不动水平放置时,测出陀螺仪和加速度计各轴的偏移值,保存.以后每次上电调用dmp_set_xx_bias()就行了. u8 run_self_test(void) ...

  9. haproxy 让后端服务器记录用户的真是IP地址(记录在header头里)

    这里我们在生产中遇到一个问题就是.我们有的用户会登录失败.但是并不是所有的用户登录失败(这里是能够正常访问网站) 所以这里想分析哪些用户登录失败,所以我们要记录他们这些登录失败的IP地址 这里我们的结 ...

  10. 如何改变git的默认路径

    1.win10下git默认启动路径是用户的根目录,东西太多太乱了. 2.修改很容易,右键单击桌面的快捷方式,选择“属性”. 3.删除“目录”中的 --cd-to-home 选项,再将“起始位置&quo ...