本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41521063

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.

通过本文你可能会学到的知识为:

(1)对基本数据类型int的最大、最小边界以及Character类的isDigit()方法有所了解。

(2)对将一个字符串转换为整形可能出现的多种情况的学习。

(3)通过算法提高自己分析问题的能力,力求考虑到尽可能多的情况。

注:

(1)int对应取值范围为-2147483648~ 2147483647

(2)Character类的isDigit()方法是判断指定字符是否为一个数字。

(3)String类的trim()方法是去掉字符串前后的空格。

思路:

(1)解读题意:

A:如果字符串为空返回0,不为空则遍历字符串,直到找到第一个是数字的字符,如果没有找到这样的字符,则返回0。

B:对于出现数字前是“+”或“-”的情况需要进行判断。

C:如果得到的数字大于int最大值或者小于int最小值,则分别返回对应的int的最大值和最小值。

(2)分析:

A:对于给定的字符串,先去掉前后的空格,看剩余字符串大小是否为空,为空则返回0;

B:如果不为空,则对其进行遍历,直到出现第一个数字字符,如果遍历完字符串还未出现数字字符,则返回0;

C:如果在遍历过程中出现数字字符,我们需要判断该数字字符前的字符,

(a) 如果该数字字符前两个字符是“+”、“-”、“  ”的组合,则为非法字符,返回0;

(b) 如果该数字字符前一个字符是“+”或者“-”,那么我们按照正和负对其进行判断,并计算当前所对应的值,对于计算的

值,我们还需要对其进行越界判断,如果越界则返回对应的越界值;

(c) 如果该数字字符前一个字符既不是“+”,也不是“-”,还不是数字字符,则为非法字符,返回0;

(d) 如果不属于以上几种情况,则说明该数字字符之前也是数字字符,则按照正常数字进行处理,先对其为正负进行判

断,判断后在对数值是否越界进行判断,最后返回判断后得到的值。需要注意的是,我们开始声明的sum为long,因

为sum的值可能会大于int的最大值,而一旦大于int的最大值,sum就会变为负值,这个要特别注意。

(3)总结:

其实这道算法题不难,只是出现的情况太多,一时很难考虑全所有的情况,我也OJ了好几次才成功。其中需要注意的是:

负数之间的相加要用减号,保存和的变量必须用long定义,在确定负号时还需要再加一个标志位对其进行判断,

例如“   -000124”这样的特殊字符。以下是我自己想的算法,算法有些啰嗦,但是思路算比较清晰,希望对大家有所帮助。

算法实现代码如下:(ps:本人技术有限,尚不能给出简短的代码,但OJ肯定通过,大家有比较好的算法希望能够分享,谢谢)

public static int atoi(String str) {
	if (str.length() == 0)
		return 0;
	long sum = 0;
	str = str.trim();
	int len = str.length();
	boolean flag = false; //当出现第一个数字时,如果后续是数字则true,不是数字则为false
	boolean negative = false; //是否为负数的判断
	for (int i = 0; i < len; i++) {
		char c = str.charAt(i);
		if (!Character.isDigit(c)) {
			if (flag == true) {   //当遇到数字后,中途再次遇到的是非数字,则将之前的值返回
				return isOutOfRange(sum);
			}
			continue;
		}

		if (Character.isDigit(c)) { //判断是否为数字
			flag = true;
			//当遇到第一个数字时,如果其前面是的两个字符是“+” “-” “ ” 的组合,则为非法字符,返回0
			if (i - 2 >= 0 && (str.charAt(i - 1) == '+'
				|| str.charAt(i - 1) == '-' || str.charAt(i - 1) == ' ')
				&& (str.charAt(i - 2) == '+'|| str.charAt(i - 2) == '-'
				|| str.charAt(i - 2) == ' ')) {
				return 0;
			} else if (i - 1 >= 0 && str.charAt(i - 1) == '+') { //如果前面只有一个“+” 则为正数
				sum = sum * 10 + Integer.parseInt(String.valueOf(c));
			} else if (i - 1 >= 0 && str.charAt(i - 1) == '-') { //如果前面只有一个“-” 则为负数
				negative = true;
				sum = -sum * 10 - Integer.parseInt(String.valueOf(c)); //负数相加要用减号
			} else if (i - 1 >= 0
					&& (str.charAt(i - 1) != '+' || str.charAt(i - 1) != '-')
					&& !Character.isDigit(str.charAt(i - 1))) { //如果前面即不是"+" 也不是"-" 还不是数字,则返回0
				return 0;
			} else {
				if (sum < 0 || negative == true) { // 对于 -00123 需要加上标志位进行判断
					if (sum < Integer.MIN_VALUE) {  //判断是否越界
						return Integer.MIN_VALUE;
					}
					sum = sum * 10 - Integer.parseInt(String.valueOf(c));
				} else {
					if (sum > Integer.MAX_VALUE) { //判断是否越界
						return Integer.MAX_VALUE;
					}
					sum = sum * 10 + Integer.parseInt(String.valueOf(c));
				}
			}
		}
	}
	return isOutOfRange(sum);
}

public static int isOutOfRange(long sum) {
	if (sum > Integer.MAX_VALUE) {
		return Integer.MAX_VALUE;
	}

	if (sum < Integer.MIN_VALUE) {
		return Integer.MIN_VALUE;
	}
	return (int) sum;
}

Leetcode_8_String to Integer的更多相关文章

  1. LeetCode 7. Reverse Integer

    Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Have you ...

  2. Integer.parseInt 引发的血案

    Integer.parseInt 处理一个空字符串, 结果出错了, 程序没有注意到,搞了很久, 引发了血案啊!! 最后,终于 观察到了, 最后的部分: Caused by: java.lang.NoC ...

  3. 由一个多线程共享Integer类变量问题引起的。。。

    最近看到一个多线程面试题,有三个线程分别打印A.B.C,请用多线程编程实现,在屏幕上循环打印10次ABCABC- 看到这个题目,首先想到的是解决方法是定义一个Integer类对象,初始化为0,由3个线 ...

  4. [LeetCode] Integer Replacement 整数替换

    Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If ...

  5. [LeetCode] Integer Break 整数拆分

    Given a positive integer n, break it into the sum of at least two positive integers and maximize the ...

  6. [LeetCode] Integer to English Words 整数转为英文单词

    Convert a non-negative integer to its english words representation. Given input is guaranteed to be ...

  7. [LeetCode] Roman to Integer 罗马数字转化成整数

    Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 t ...

  8. [LeetCode] Integer to Roman 整数转化成罗马数字

    Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 t ...

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

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

随机推荐

  1. spring cloud 入门系列三:使用Eureka 搭建高可用服务注册中心

    在上一篇中分享了如何使用Eureka 进行服务治理,里面搭建的服务注册中心是单体的, 但是在实际的应用中,分布式系统为了防止单体服务宕机带来严重后果,一般都会采用服务器集群的形式,服务注册中心也是一样 ...

  2. 剑指架构师系列-Redis集群部署

    初步搭建Redis集群 克隆已经安装Redis的虚拟机,我们使用这两个虚拟机中的Redis来搭建集群. master:192.168.2.129 端口:7001 slave:192.168.2.132 ...

  3. HashMap 和 HashTable 区别

    来源:http://www.importnew.com/7010.html HashMap和Hashtable的区别 HashMap和Hashtable都实现了Map接口,但决定用哪一个之前先要弄清楚 ...

  4. MySQL NULL 值处理

    MySQL NULL 值处理 我们已经知道MySQL使用 SQL SELECT 命令及 WHERE 子句来读取数据表中的数据,但是当提供的查询条件字段为 NULL 时,该命令可能就无法正常工作. 为了 ...

  5. Docker Hub

    目前 Docker 官方维护了一个公共仓库 Docker Hub,其中已经包括了超过 15,000 的镜像.大部分需求,都可以通过在 Docker Hub 中直接下载镜像来实现. 登录 可以通过执行 ...

  6. nginx 日志分析工具goaccess

    参考:https://www.goaccess.io/download 安装 $ wget http://tar.goaccess.io/goaccess-1.1.1.tar.gz $ tar -xz ...

  7. Linux下文件的mtime/atime/ctime研究

    概述 在Linux下,对于某一个文件或文件夹时间的描述有三种:文件修改时间mtime,文件访问时间atime,文件状态改变时间ctime.在Linux下无法获取到文件的创建时间,因为根本就没有保存这个 ...

  8. Android Studio精彩案例(二)《仿微信动态点击底部tab切换Fragment》

    转载本专栏文章,请注明出处,尊重原创 .文章博客地址:道龙的博客 现在很多的App要么顶部带有tab,要么就底部带有tab.用户通过点击tab从而切换不同的页面(大部分情况时去切换fragment). ...

  9. 深度学习与计算机视觉系列(2)_图像分类与KNN

    作者: 寒小阳 &&龙心尘 时间:2015年11月. 出处: http://blog.csdn.net/han_xiaoyang/article/details/49949535 ht ...

  10. ROS机器人程序设计(原书第2版)补充资料 (伍) 第五章 计算机视觉

    ROS机器人程序设计(原书第2版)补充资料 (伍) 第五章 计算机视觉 书中,大部分出现hydro的地方,直接替换为indigo或jade或kinetic,即可在对应版本中使用. 计算机视觉这章分为两 ...