[leetcode]String to Integer (atoi)

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   strong   for   

String to Integer (atoi)

 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.

演算法思路:

坑比較多,沒難度。開整之前建議先把str預先處理一下

【注意】邊界case:

全空格、全非法字元、空串<-這三種預先處理之後都變成空串了。

溢出。因此先把result聲明成long型。

符號處理:

兩個boolean變數表示加號或減號,但是一旦有了某個符號,第二個符號就變成非法字元了。字串中未出現符號,按照正號處理。

代碼如下:

 1 public class Solution { 2     public int atoi(String str) { 3         if(str == null || str.trim().length() == 0) return 0; 4         str = str.trim(); 5         StringBuilder sb = new StringBuilder(); 6         int length = str.length(); 7         ////preprocess,only maintain num and operater 8         for(int i = 0; i < length; i++){ 9             if(str.charAt(i) == ‘+‘ || str.charAt(i) == ‘-‘  || (str.charAt(i) <= ‘9‘ && str.charAt(i) >= ‘0‘)){10                 sb.append(str.charAt(i));11             }else break;12         }13         length = sb.length();14         boolean positive = false,negative = false;15         long res = 0;16         for(int i = 0; i < length; i++){17             //the second time appearrance of operater is invalide18             if((sb.charAt(i) == ‘+‘ || sb.charAt(i) == ‘-‘) && (positive || negative)) 19                 break;20             if(sb.charAt(i) == ‘+‘){21                 positive = true;22             }else if(sb.charAt(i) == ‘-‘){23                 negative = true;24             }else{25                 res = res * 10 + (sb.charAt(i) - ‘0‘);26             }27         }28         if(!positive && !negative) positive = true;29         // process overflow situation30         if(positive) return res > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) res;31         return res > Integer.MAX_VALUE ? Integer.MIN_VALUE : (int)res * -1;        32     }33 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.