peace唠叨

leetcode08- String to Integer (atoi)之Java版本

我的leetcode之旅,该篇章主要完成使用Java实现算法。这是第8篇String to Integer (atoi)

全部代码下载:Github链接:github链接,点击惊喜;写文章不易,欢迎大家采我的文章,以及给出有用的评论,当然大家也可以关注一下我的github;多谢;

1.题目简介:

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.


Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

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.


2.我的思路:

1.题目是挺easy的,主要是对一些特殊输出进行考虑
2.特殊状况详情见我的注释

3.我的AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.rlovep.int1;
/**
* String to Integer (atoi)
* 我的思路:
* 题目是挺easy的,主要是对一些特殊输出进行考虑
* 特殊状况详情见我的注释
* @author peace
*
*/

public class Atoi {
public static int myAtoi(String str) {
long res=0; //使用long型主要是为了防止超过int的限制
long out=2147483648L;//当res技术大于out时证明已经过量,可以结束对剩余的转型
if(str==null||"".equals(str))return 0;//对字符串为null和空的考虑
int i=0;//记录字符位置索引
str=str.trim();//去除开头和结尾的空格字符
int length=str.length();//获得字符串长度
boolean flag=true;
if(str.charAt(i)=='+'||str.charAt(i)=='-'){
if(length<2)return 0;//当字符串只有一个符号位时,直接返回
if(str.charAt(i)=='-') flag=false;//正负号判断标志
i++;
}
for(;i<length;i++)
{
int c=str.charAt(i)-'0';//获得转型的整数
if(c>=0&&c<=9){
res=res*10+c;//进行转换
if(res>out)break;//判断是否过量
}else{
break;//出现非法字符,结束转型
}
}
if(flag==false)res=-res;
if(res>2147483647)res=2147483647;//正数过量时输出正数最大值
if(res<-2147483648)res=-2147483648;//负数过量时输出负数最大值
return (int)res;
}
public static void main(String[] args) {
System.out.println(myAtoi("9223372036854775809"));
}
}

好的本章介绍到这里 来自伊豚wpeace(blog.wpeace.cn)

Peace wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!