String to Integer (atoi)

經典的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"));
    	   
       }
}



發佈了42 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章