String to Integer (atoi)

来源:互联网 发布:建模 软件 数据 开源 编辑:程序博客网 时间:2024/04/30 11:18

经典的atoi函数

写起来还真是大费周折。

atoi函数要满足一下几个条件:

0.整型字符包括0-9、‘+’、‘-’。

1.一开始如果是空格的话,省略掉空格。

2.如果字符串前一部分满足整型要求,后面是不满足整型要求的字符,则只输出前面满足的部分。

3.如果一开始就是非整型字符,则输出0.解决方法是加一个布尔变量判断是否已经开始输入整型字符。

4.整型越界后,要输出越界的范围。大于INT_MAX则输出INT_MAX,小于INT_MIN则输出INT_MIN。

以INT_MAX为例,判断条件是a、b条件满足其中之一即可直接输出

a)INT_MAX-value*10<str[indexStr]-'0'。

b)value已经达到10位数。


如果用正则表达式是不是可以大量简化?


上代码:

public class Solution {    public int atoi(String str) {        int value=0;        boolean startInt=false;//开始输入整型字符        boolean isNegtive=false;//正负判断        int count=0;        for(int indexStr=0;indexStr<str.length();++indexStr)        {            if(!startInt&&str.charAt(indexStr)==' ')continue;            if(!startInt&&(str.charAt(indexStr)=='+'||str.charAt(indexStr)=='-'))             {                isNegtive=str.charAt(indexStr)=='-'?true:false;                startInt=true;                continue;             }                         if(str.charAt(indexStr)>='0'&&str.charAt(indexStr)<='9')            {                                        if(isNegtive&&value!=0&&(count>=10||             (value!=0&&(value*10-Integer.MIN_VALUE<(str.charAt(indexStr)-'0'))))             )return Integer.MIN_VALUE;             else if(             !isNegtive&&value!=0&&(             (count>=10||(Integer.MAX_VALUE-value*10)<(str.charAt(indexStr)-'0'))))return Integer.MAX_VALUE;             if(isNegtive)             {value=value*10-(str.charAt(indexStr)-'0');count++;}             else {value=value*10+(str.charAt(indexStr)-'0');count++;}                          startInt=true;                         }            else return value;                                         }        return value;    }       public static void main(String[] args){       System.out.print(new Solution().atoi("    2147483646"));              }}



0 0
原创粉丝点击