LeetCode第八題, String to Integer (atoi),leetcodeatoi
題目原文
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.
spoilers alert... click to show requirements for atoi.
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.
題意
實現atoi
1 數字開頭可能有空格
2 有符號
3 中間有字母處理字母之前的數字
4 有溢出 輸出最大/最小
5 比較大小的話用 longlong 就沒問題了
代碼:
class Solution: # @return an integer def atoi(self, str): str = str.strip() newStr = [] for i in xrange(len(str)): if '0' <= str[i] <= '9' or (str[i] in ('+', '-') and i == 0): newStr.append(str[i]) else: break if newStr in ([], ['+'], ['-']): return 0 elif -2147483648 <= int(''.join(newStr)) <= 2147483647: return int(''.join(newStr)) elif int(''.join(newStr)) > 2147483647: return 2147483647 else: return -2147483648
leetcode中multiply strings出現runtime error,解
leetcode的定位是面試題,不是ACM題
也就是說題目並不是以AC與否來判斷你的答案正確與否的
更重要的是面試的時候給別人的感覺
這本來是一道考察字串表示大數和大叔乘法的題,po主卻用上了stringstream和vector
在面試裡面這樣的答案哪怕最後能得到正確的結果,也不會給面試官留下好的印象。
我會幫你偵錯工具,但是我還是覺得你重新寫一份簡單易懂的更好,避免使用STL和流
C++對於返回string的情況?為何我在dev c++與vc60下測試都過?但是在leetcode上過不了?
Runtime Error這個錯誤不是說你的程式不能編譯,而是說你的程式在運行期間出現了錯誤。這樣的錯誤一般是數組越界訪問,棧溢出,訪問非法記憶體所造成的。