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. nginx 实现valid_referer全面解析

    先来补充点知识,然后在进行讲解. 先看下两种HTTP head 一个是直接输入网址打开的head,另一个是通过搜索引擎打开的网址head 一:直接输入网址打开的 (Request-Line)  GET ...

  2. 树莓派 SD卡镜像备份

    一.准备工作 1.已经配置启动的树莓派SD卡 2.Linux系统的pc 3.读卡器 二.修改SD卡文件 刚开始我先再win7下把SD卡接到pc上,发现无法读取.用DISKGENIUS查看pc的磁盘状态 ...

  3. Linux中tomcat启动很慢,SessionIdGeneratorBase.createSecureRandom耗时5分钟

    通常情况下,tomcat启动只要2~3秒钟,突然有一天,tomcat启动非常慢,要花5~6分钟,查了很久,终于在这篇文章找到了解决方案,博主牛人啊. 原文参见:http://blog.csdn.NET ...

  4. 跟我学SharePoint 2013视频培训课程—— 审批、拒绝列表项(13)

    课程简介 第13天,怎样在SharePoint 2013中审批.拒绝列表项. 视频 SharePoint 2013 交流群 41032413

  5. FreeSWITCH媒体转码配置

    一.说明: FreeSWITCH版本1.6.13二.测试准备 软电话A的语音编码只配置iLBC:软电话B的语音编码只配置PCMU: A->B,编码协商失败,收到488消息. 三.修改文件vars ...

  6. jlink下载不进去程序

  7. tensorflow中使用Batch Normalization

    在深度学习中为了提高训练速度,经常会使用一些正正则化方法,如L2.dropout,后来Sergey Ioffe 等人提出Batch Normalization方法,可以防止数据分布的变化,影响神经网络 ...

  8. 微信小程序-实现分享(带参数)

    微信小程序分享功能的实现方法有两种: 第一种 在page.js中实现onShareAppMessage,便可在小程序右上角选择分享该页面 onShareAppMessage: function () ...

  9. hive元数据研究

    hive的元数据存放在关系型数据库中,元数据中存储了hive中所有表格的信息,包括表格的名字,表格的字段,字段的类型,注释.这些信息分散的存放在各个表中,给定一个hive中的表格名字,查询这个表中含有 ...

  10. Git--团队开发必备神器

    花了两天时间专门搞了一下git.整理一下分享给大家.以下我们開始.. . 转载请注明出处: http://blog.csdn.net/Hello_Chillax/article/details/474 ...