No.008:String to Integer (atoi)
问题:
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases.
官方难度:
Easy
翻译:
实现atoi功能,将一个字符串转化成一个整数。
提示:仔细考虑各种可能出现的情况。
补充资料:
所谓atoi,是C语言库中的一个函数,其功能如下:
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.
函数atoi要求:
- 丢弃第一个非空格字符串之前的所有字符串。
- 剩余字符串接受以“+”或“-”操作符起始的数字,在遇到下一个非数值字符串之前,截取尽可能多的字符串,将其转化成数值。
- 忽略之后遇到的非数值字符串。如果第一个非空格字符串不是数值,或者原字符串就是空格字符组成,抑或是空字符串,那么不做转换。
- 如果不做转换,函数返回0;如果结果超出int型能表达的最大/最小值,返回整型数的最大/最小值。
- 先去除原字符串的前后空格,使用String.trim()方法。
- 处理之后的字符串,做长度为0的特殊处理,返回0。
- 记录第一个是“+”或“-”操作符的情况,利用一个标志位记录,在返回时使用,同时将这个位置用字符0替换,不影响之后的累加操作。
- 记录遇到第一个非数值字符之前的长度length。
- 累加数值,这里要注意两点。第一点,length作为循环退出条件,又要在操作中自减,所以需要准备一个副本;第二点,char型的字符,用于数值计算,使用array[i]-‘0’来表示当前的数值。
- 用long型的sum来记录累加的数值,乘以标志位置后做超出范围操作。
- 注意入参检查。
解题代码:
public static int myAtoi(String str) {
if (str == null) {
throw new IllegalArgumentException("Input error");
}
// 先去空格
char[] array = str.trim().toCharArray();
// 0特殊处理
if (array.length == 0) {
return 0;
}
// 正负号标志位
int sign = 1;
long sum = 0;
if (array[0] == '+' || array[0] == '-' || (array[0] >= '0' && array[0] <= '9')) {
// 操作符置char型的'0'
if (array[0] == '+') {
array[0] = '0';
sign = 1;
} else if (array[0] == '-') {
array[0] = '0';
sign = -1;
}
// 循环确定长度
int length = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] >= '0' && array[i] <= '9') {
length++;
} else {
// 遇到非数值退出循环
break;
}
}
// length值作为退出条件,但同时又要自减,准备一个副本
int exit = length;
for (int i = 0; i < exit; i++) {
// char型的数值,转换成数值型处理
sum += (array[i] - '0') * Math.pow(10, --length);
}
// 超出范围处理
long num = sum * sign;
if (num > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (num < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) num;
} else {
return 0;
}
}
myAtoi
相关链接:
https://leetcode.com/problems/string-to-integer-atoi/
PS:如有不正确或提高效率的方法,欢迎留言,谢谢!
No.008:String to Integer (atoi)的更多相关文章
- Q8:String to Integer (atoi)
8. String to Integer (atoi) 官方的链接:8. String to Integer (atoi) Description : Implement atoi to conver ...
- leetcode:String to Integer (atoi)
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- No.008 String to Integer (atoi)
8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...
- LeetCode--No.008 String to Integer (atoi)
8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...
- 《LeetBook》leetcode题解(8): String to Integer (atoi) [E]——正负号处理
我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...
- 【leetcode】String to Integer (atoi)
String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...
- leetcode day6 -- String to Integer (atoi) && 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 ...
- Kotlin实现LeetCode算法题之String to Integer (atoi)
题目String to Integer (atoi)(难度Medium) 大意是找出给定字串开头部分的整型数值,忽略开头的空格,注意符号,对超出Integer的数做取边界值处理. 方案1 class ...
- 【Leet Code】String to Integer (atoi) ——常考类型题
String to Integer (atoi) Total Accepted: 15482 Total Submissions: 106043My Submissions Implement ato ...
随机推荐
- OpenGL学习资料汇总
我学OpenGL的3D编程也有1.2个年头了,走了很多弯路,也算有点收获.现在整理出一些好用的资料如下. NeHe OpenGL教程中文版 地址(http://www.yakergong.net/ne ...
- js实用篇之String对象
概述 String对象是JavaScript原生提供的三个包装对象之一,用来生成字符串的包装对象. var s1 = 'abc'; var s2 = new String('abc'); typeof ...
- ASP.NET列表信息以Excel形式导出
1.从数据查出数据扔进table中: private DataTable getTable() { var dbHelper = applyBLL.CreateDataBase("VISAd ...
- Atitit 分区后的查询 mysql分区记录的流程与原理
Atitit 分区后的查询 mysql分区记录的流程与原理 1.1.1. ibd是MySQL数据文件.索引文件1 1.2. 已经又数据了,如何分区? 给已有的表加上分区 ]1 1.3. 分成4个区, ...
- [转] Android优秀开源项目
Android经典的开源项目其实非常多,但是国内的博客总是拿着N年前的一篇复制来复制去,实在是不利于新手学习.今天爬爬把自己熟悉的一些开源项目整理起来,希望能对Android开发同学们有所帮助.另外, ...
- G2 2.0 更灵活、更强大、更完备的可视化引擎!
概述 G2作为一款技术产品,自诞生以来,服务于广大的Web工程师群体和一部分数据分析师.一直来,G2 因其易用的语法和扎实的可视化理论基础,广受使用者好评.G2 1.x 的可视化能力已经非常强大,使用 ...
- Ajax概要:
Ajax概要: Ajax不是个全新的技术,它是多种技术合并在一起产生的,包括XHTML,CSS,JavaScript,XmlHttpRequest,XML,JSON,DOM等 优点:(这也解释了为何我 ...
- 免费获取WP之类的开发者权限或免费使用Azure 2015-10-19
上一次弄wp真机调试的时候,卡住了,这里讲一下怎么解决(http://www.cnblogs.com/dunitian/p/4870959.html) 进这个网址注册一下:https://www.dr ...
- 传智播客--XAML布局--连连看界面(小白内容)
一个简单的10*10连连看,有100个格子,可以在XAML里面用ColumnDefinition和RowDefinition各写10组,但是这样效率会很慢,因此,可以采用动态生成的方式进行. publ ...
- 深入理解客户区尺寸client
前面的话 关于元素尺寸,一般地,有偏移大小offset.客户区大小client和滚动大小scroll.前文已经介绍过偏移属性,后文将介绍scroll滚动大小,本文主要介绍客户区大小client 客户区 ...