leetcode atoi java_LeetCode【8】. String to Integer (atoi) --java实现

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 thefirst sequence of non-whitespace charactersin 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;

2、该合法数值子字符串中或后,可能包含其他非数值的特殊字符,忽略这些子字符串;

3、若第一个非空子字符串非护法的整型数值,或根本就没有,甚至该字符串可能都是特殊字符或空字符,则不作转换0;

4、若没有有效地转换,则返回0,若有返回数值超出边界,则返回边界值;

一、思路:

本题虽然属于比较简单的级别,但是在没考虑好全部可能的情况下,总是会出现遗漏一些细节的结果,导致提交后总是有新的意外情况出现。如:“     +-15651”、“    *    6644”这些首次出现的字符串不能构成数字的都是属于不合法的情况,直接返回0。思路如下:先扫描到第一个非空字符,再考虑两种情况,第一种是第一个非空字符是'+'或'-'号,若是则继续判断接下来的字符是否为数字,不是则不合法;另外一种是第一个非空字符是数字,那可继续以扫描数字的方式进行转换。除了以上两种情况,其他都为不合法。

二、Java程序

public class Solution {

public int myAtoi(String str) {

int sl = str.length();

int index=0;

char tempc; //获取字符

boolean flag = false; //负数标志

int firstI=-1;

long re=0;

if(sl<=0)

return 0;

//1. 开始至第一个非空字符

while(str.charAt(index)==' ')

{

index++;

if(index>=sl) //超过字符串长度

return 0;

}

//2. 扫到第一个非空字符,判断是否合法

tempc = str.charAt(index);

//2.1 若是+-或数值则进行,否则则返回0

if(tempc=='-'||tempc=='+'||(tempc<='9'&&tempc>='0'))

{

//2.2 若是数值则跳出判断

if((tempc<='9'&&tempc>='0'))

{

}else //2.3 若是+-号,则判断接下来的是否为数值

{

if(tempc=='-') flag = true;//2.3.1 若是-号,则设置标志位

index++; //2.4 若是+-号,则判断下一位是不是数值,是则合法,不是则返回0

tempc = str.charAt(index);

if((tempc<='9'&&tempc>='0'))

{}else

{

return 0;

}

}

}else //2.1 若是+-或数值则进行,否则则跳出

{

return 0;

}

//3. 开始扫描有效数字

while(index

{

tempc = str.charAt(index);

if(tempc<='9'&&tempc>='0')

{

re = re*10 + (str.charAt(index)-'0');

if(re>=Integer.MAX_VALUE||re<=Integer.MIN_VALUE)

break;

}else

{

break;

}

index++;

}

if(flag==true)

{ re=-re;

re = re

}else

{

re = re>Integer.MAX_VALUE?Integer.MAX_VALUE:re;

}

return (int)re;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值