008 String to Integer (atoi)[M]
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.
難度:Medium
2 題目樣例
無。
3 題目分析
題意非常的容易理解...就是想讓你手動實現一下atio函數。(一個能把string類型的字元串整數,轉化為int類型整數的函數)
一開始我本以為這個題目無比的簡單...AC的道路將會無比通暢......
但是我忽略了這道題目的正確率。
隨手翻了翻,沒看到比這個題目正確率(%13.9)再低的題目了。
既然正確率低,題目本身還不難,那就說明題目中的坑點一定很多。好在題目中還給了我們一定的提示。
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.
還有一些更加特殊的情況...比如說輸入的是個空字元串之類的。通通特判就好。
注意到了這幾點,大概解題會變得更加輕鬆一點吧...
4 思路分析
和上一道題目類似。利用一個long long類型的變數來存儲結果,利用一個int類型的sign變數來記錄符號。利用一個計數器i來起到類似於字元指針的作用。
代碼實現如下:
class Solution nn{npublic:n n int myAtoi(string str) n n {n if(str.size()==0) return 0;n n long long result=0;n n int sign=1;n n int i=0;n n int n=str.size();n n while(i<n && str[i]== ) ++i;n n if(str[i]==+||str[i]==-) n n if(str[i++]==+) sign=1;n n else sign=-1;n n while(i<n && str[i]>=0 && str[i]<=9)n n {n result =result*10+(str[i++]-0);n n if(result*sign>=INT_MAX) return INT_MAX;n n if(result*sign<=INT_MIN) return INT_MIN;n }n n return result*sign;n }n};n
5 後記
題目本身是不難的...但是想一遍AC確實很考驗程序設計者的思維嚴謹性啊!
推薦閱讀:
※003 Longest Substring Without Repeating Characters[M]
※有哪些非常有意思的ACM題目?
※演算法分析從入門到深入,求書籍推薦?
※怎樣判斷平面上一個矩形和一個圓形是否有重疊?