2015年12月19日 星期六

[LC8] 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.
題目要求: 
實作 atoi, 把 string轉成 int。
 思路:
字串前端的空白必須要完全略過 (利用一個 while迴圈來達成),緊接著可能會是 '+' or '-' 字元來表示數字的正負號 (利用 if 判斷式讀進來)。接下來就用 ASCII code來判斷是否為數字字元,並跟上一題一樣,把數字一個個串上去結果整數,並特別注意 integer overflow即可。當讀到非數字時,return 目前已經有的數字。
實作
Time complexity: O(n)

沒有留言:

張貼留言