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.

抠细节的题目,特别是 Integer.MIN_VALUE 与 Integer.MAX_VALUE的绝对值并不一样大. 一般要分开处理,但我这里16-17行统一处理也是可行的,原因在于用的是>号,当res 绝对值为2147483647时,给res加正号或者加负号都是可以的,不需要特殊处理;只有当res绝对值为2147483648或更大时才需要特别处理,如果是正数则处理为Integer.MAX_VALUE,如果是负数则处理为Integer.MIN_VALUE(与直接给2147483648加上负号效果一样)。整数一般有两点,一个是正负符号问题,另一个是整数越界问题。

 public class Solution {
public int atoi(String str) {
int res = 0;
if (str==null || str.length()==0) return res;
str = str.trim();
if (str.length() == 0) return res;
boolean isNeg = false;
for (int i=0; i<str.length(); i++) {
if (i == 0 && str.charAt(i) == '+') continue;
else if (i == 0 && str.charAt(i) == '-') {
isNeg = true;
continue;
}
else if (str.charAt(i)>='0' && str.charAt(i)<='9') {
int digit = (int)(str.charAt(i) - '0');
if (res > (Integer.MAX_VALUE - digit) / 10) {
return isNeg? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
res = res * 10 + digit;
}
else break;
}
return isNeg? -res : res;
}
}

转载一个不错的解法(跟我差不多):

 public int atoi(String str) {
if(str==null)
{
return 0;
}
str = str.trim();
if(str.length()==0)
return 0;
boolean isNeg = false;
int i = 0;
if(str.charAt(0)=='-' || str.charAt(0)=='+')
{
i++;
if(str.charAt(0)=='-')
isNeg = true;
}
int res = 0;
while(i<str.length())
{
if(str.charAt(i)<'0'||str.charAt(i)>'9')
break;
int digit = (int)(str.charAt(i)-'0');
if(isNeg && res>-((Integer.MIN_VALUE+digit)/10))
return Integer.MIN_VALUE;
else if(!isNeg && res>(Integer.MAX_VALUE-digit)/10)
return Integer.MAX_VALUE;
res = res*10+digit;
i++;
}
return isNeg?-res:res;
}

Leetcode: String to Integer的更多相关文章

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

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

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

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

  3. [LeetCode]String to Integer (atoi)

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

  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]String to Integer (atoi) 简易实现方法

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

  7. leetcode String to Integer (atoi) python

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

  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. NSQ:分布式的实时消息平台

    NSQ是一个基于Go语言的分布式实时消息平台,它基于MIT开源协议发布,代码托管在GitHub,其当前最新版本是0.3.1版.NSQ可用于大规模系统中的实时消息服务,并且每天能够处理数亿级别的消息,其 ...

  2. Delphi出现“borland license information was found,but it is not valid for delphi”的错误,无法运行的解决方法

    1) 删除文件: C:\documents and settings\<username>\.borland\registry.slm,如果在win8或在win7下,即C:\Users\H ...

  3. android studio 出错

    http://blog.csdn.net/dhx20022889/article/details/44919905

  4. 初始Spring

    Spring框架概述 1.什么是Spring struts2----是web层框架,围绕请求和响应 Hibernate----是持久层框架,围绕业务的增删改查 Spring是分层的JavaSE/EE ...

  5. php://input,$_POST,$HTTP_RAW_POST_DATA区别

    我们先来看两个demo 例子:php://input 代码如下   post.php 代码如下   例子:$_post 代码如下   welcome.php 代码如下   再来看$GLOBALS [& ...

  6. linux 查看系统状态方法

    Linux下如何查看系统启动时间和运行时间 1.uptime命令输出:16:11:40 up 59 days, 4:21, 2 users, load average: 0.00, 0.01, 0.0 ...

  7. iOS开发入门教程

    iOS开发入门教程 http://my.oschina.net/mailzwj/blog/133273 摘要 iOS开发入门教程,从创建项目到运行项目,包括OC基础,调试,模拟器设置等相关知识. iO ...

  8. 读书笔记——《图解TCP/IP》(3/4)

    经典摘抄 第五章 IP协议相关技术 1.DNS可以将网址自动转换为具体的IP地址. 2.主机识别码的识别方式:为每台计算机赋以唯一的主机名,在进行网络通信时,可以直接使用主机名称而无需输入一大长串的I ...

  9. 20145211 《Java程序设计》第1周学习总结——小荷才露尖尖角

    教材学习内容总结 Java语言概述 Java是SUN1995年推出的一门高级编程语言,完全面向对象,安全可靠,具有跨平台性(用其编写的语言在任何系统上都能运行,只需安装一个JVM) Java三大平台包 ...

  10. Subset---poj3977(折半枚举+二分查找)

    题目链接:http://poj.org/problem?id=3977 给你n个数,找到一个子集,使得这个子集的和的绝对值是最小的,如果有多种情况,输出子集个数最少的: n<=35,|a[i]| ...