问题描述:

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.

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.

解题思路:

首先调用trim方法除去字符串两边的空白字符。然后从开头读起,如果开头为‘+’,表明该值为正数;如果开头为‘-’,表明该值为负数;如果第一个读到的是‘+’或者‘-’,则从第二个开始读,否则仍然从第一个读起。下面开始一直往后读直到字符串结束。如果在读的过程中读到了除字符’0‘-’9'以外的数字,那么跳出循环,返回计算好的值,否则,不停的计算累加值。

代码如下:

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

Java [leetcode 8] String to Integer (atoi)的更多相关文章

  1. Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)

    Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串) 题目描述 实现atoi函数,将一个字符串转化为数字 测试样例 Input: "42&q ...

  2. 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 ...

  3. 【leetcode】String to Integer (atoi)

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

  4. [leetcode] 8. String to Integer (atoi) (Medium)

    实现字符串转整形数字 遵循几个规则: 1. 函数首先丢弃尽可能多的空格字符,直到找到第一个非空格字符. 2. 此时取初始加号或减号. 3. 后面跟着尽可能多的数字,并将它们解释为一个数值. 4. 字符 ...

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

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

  6. [LeetCode][Python]String to Integer (atoi)

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/string- ...

  7. 【JAVA、C++】 LeetCode 008 String to Integer (atoi)

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

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

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

  9. LeetCode 8. String to Integer (atoi) (字符串到整数)

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

随机推荐

  1. 【机器学习】BP神经网络实现手写数字识别

    最近用python写了一个实现手写数字识别的BP神经网络,BP的推导到处都是,但是一动手才知道,会理论推导跟实现它是两回事.关于BP神经网络的实现网上有一些代码,可惜或多或少都有各种问题,在下手写了一 ...

  2. [转]GLES 3.0 新特性

    转自: http://www.ifanr.com/131333 OpenGL ES 3.0 带来很多新特性,根据 AnandTech 的解释: 支持更多缓冲区对象.在 OpenGL ES 2.0 时中 ...

  3. jQuery.validate errorPlacement

    在被验证的控件的后一个元素控制显示 errorPlacement: function(error, element) { element.next().css("color",&q ...

  4. 【设计模式六大原则6】开闭原则(Open Close Principle)

      定义:一个软件实体如类.模块和函数应该对扩展开放,对修改关闭. 问题由来:在软件的生命周期内,因为变化.升级和维护等原因需要对软件原有代码进行修改时,可能会给旧代码中引入错误,也可能会使我们不得不 ...

  5. Corner case

    A corner case (or pathological case) is a problem or situation that occurs only outside of normal op ...

  6. mySql 自动备份数据库

    mysqldump -u root -proot -h 192.168.1.100 xqpd > 1.sqlcopy 1.sql D:\项目备份\工程_数据库-%date:~0,4%%date: ...

  7. POJ2186 Popular Cows 强连通分量tarjan

    做这题主要是为了学习一下tarjan的强连通分量,因为包括桥,双连通分量,强连通分量很多的求法其实都可以源于tarjan的这种方法,通过一个low,pre数组求出来. 题意:给你许多的A->B ...

  8. 【QT】视频播放+文件选择

    折腾了两个小时,太久没用了,找了半天的感觉. 先是在视频播放 的代码基础上加选择视频的按钮,开始总是显示两个框,后来发现需要用QSplitter来实现同时有多个框的情况. 把中心窗口设为这个split ...

  9. js注册验证【转】

    function getFocus() //设置用户名文本框获取焦点 { document.getElementById("txtuname").focus(); } functi ...

  10. http://jingyan.baidu.com/article/08b6a591f0fafc14a9092275.html

    http://jingyan.baidu.com/article/08b6a591f0fafc14a9092275.html http://jingyan.baidu.com/article/414e ...