问题描述:

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. tomcat 运行异常Cannot create PoolableConnectionFactory (到主机 的 TCP/IP 联接失败)(用户sa登录失败)

    这是在java web中启动tomcat遇到的问题,因为这个问题,整整折腾了两天的时间,找了很都解决方案,但终究还是不能正常.现在整理下这个问题的解决方案: 首先,出这个问题之前,请检查一下的问题,这 ...

  2. Codeforces Round #362 (Div. 2)->A. Pineapple Incident

    A. Pineapple Incident time limit per test 1 second memory limit per test 256 megabytes input standar ...

  3. Restore IP Addresses

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  4. struts2 json关于Date日期的解析

    在get方法前加上: @JSON(format="yyyy-MM-dd HH:mm:ss")

  5. selenium2 安装、简单使用及浏览器启动问题解决汇总

    一.selenium2 安装 1.安装jdk并配置环境变量 jdk需要1.6版本及以上的,这个从网上下载就可以,环境变量的配置前边的随笔整理过就不多说了. 2.安装Firefox,Selenium I ...

  6. cojs 火龙果 解题报告

    昨天晚上做了一发HNOI,感觉有很多新的idea 于是就选了一个出成题目辣 我们考虑暴力 暴力很明显是把这个图A<=D,B<=E的形态搞出来 之后处理相关的询问 这样我们会很容易得到正解: ...

  7. 用Delphi创建服务程序

    用Delphi创建服务程序 日期:2005年11月29日 作者:sunmohe 人气: 3154 查看:[大字体 中字体 小字体] Windows 2000/XP和2003等支持一种叫做"服 ...

  8. 李洪强iOS开发之OC[014] -对象的存储细节

    // //  main.m //  13 - 对象的存储细节 // //  Created by vic fan on 16/7/9. //  Copyright © 2016年 李洪强. All r ...

  9. Matlab程序 转C++/Opencv基于Mat 不可不知的17个函数

    1.matlab中的imread相当于OpenCV中的cvLoadImage(imageName,  CV_LOAD_IAMGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR): ...

  10. 【Linux高频命令专题(16)】less

    概述 less 工具也是对文件或其它输出进行分页显示的工具,应该说是linux正统查看文件内容的工具,功能极其强大.less 的用法比起 more 更加的有弹性.在 more 的时候,我们并没有办法向 ...