8. 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.
Update (2015-02-10):
The signature of the?C++?function had been updated. If you still see your function signature accepts a?const char *?argument, please click the reload button??to reset your code definition.
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.
鏈接:http://leetcode.com/problems/string-to-integer-atoi/
題解:
這道題試了好多次才ac,在Microsoft onsite的第三輪里也被問到過如何解決和測試。主要難點就是處理各種corner case。假如面試中遇到,一定要和面試官多溝通交流,確定overflow,underflow以及invalid的時候,應該返回什么值。判斷時不可以使用long才hold溢出情況,一般都是比較當前數值和Integer.MAX_VALUE / 10 或者Integer.MIN_VALUE / 10。
以下是一個AC解法,主要方法是
1). 判斷輸入是否為空
2). 用trim()去除string前后的空格
3). 判斷符號
4). 假如符號位后連續幾位是有效的數字,對數字進行計算,同時判斷是否overflow或者underflow。
5). 返回數字
public class Solution {public int myAtoi(String str) {if(str == null || str.length() == 0)return 0;str = str.trim();int index = 0, result = 0;boolean isNeg = false;if(str.charAt(index) == '+')index ++;else if(str.charAt(index) == '-'){isNeg = true;index ++;}while(index < str.length() && str.charAt(index) >= '0' && str.charAt(index) <= '9'){ //deal with valid input numbersif(result > Integer.MAX_VALUE / 10){return isNeg ? Integer.MIN_VALUE : Integer.MAX_VALUE; // case " -11919730356x", the result should be 0? } else if( result == Integer.MAX_VALUE / 10){ if((!isNeg) && ((str.charAt(index) - '0') > Integer.MAX_VALUE % 10) ) return Integer.MAX_VALUE;else if (isNeg && ((str.charAt(index) - '0') > (Integer.MAX_VALUE % 10 + 1)))return Integer.MIN_VALUE;}result = result * 10 + (str.charAt(index) - '0'); index ++; }return isNeg ? -result : result;} }Python:
Java式Python... sigh,不知道什么時候才可以寫得優雅簡練。 ? 檢查Python里字符是否為數字一般有兩種方法,一種是c.isdigit(), 另外可以嘗試用try catch
try:int(c) except ValueError:pass?
Time Complexity - O(n), ?Space Complexity - O(1)
class Solution(object):max_value = 2147483647min_value = -2147483648def myAtoi(self, str):""":type str: str:rtype: int"""if str == None or len(str) == 0:return 0index = 0while str[index] == ' ':index += 1sign = 1if str[index] in ('+', '-'):if str[index] == '-':sign = -1index += 1res = 0 while index < len(str):c = str[index]num = 0if c.isdigit():num = int(c)if res > self.max_value / 10:return self.max_value if sign == 1 else self.min_valueelif res == self.max_value / 10:if sign == -1 and num > 8:return self.min_valueelif sign == 1 and num > 7:return self.max_valueres = res * 10 + numelse:return res * signindex += 1return res * sign?
測試:
1.?"+-2"
2. " ? ?123 ?456"
3. " ? ? ?-11919730356x"
4. "2147483647"
5. "-2147483648"
6. "2147483648"
7. "-2147483649"
?
二刷:
Time Complexity - O(n), Space Complexity - O(1)
Java: 二刷思路就比較清晰。依然是有下面幾個步驟:
這里比較tricky的點是,從Integer.MAX_VALUE和Integer.MIN_VALUE越界時要分別返回Integer.MAX_VALUE或者Integer.MIN_VALUE。假如當前字符不為數字,則返回之前已經計算過的,到這一位為止的res * sign。
public class Solution {public int myAtoi(String str) {if (str == null || str.length() == 0) {return 0;}int index = 0;while (str.charAt(index) == ' ') {index++;}int sign = 1;if (str.charAt(index) == '+' || str.charAt(index) == '-') {if (str.charAt(index) == '-') {sign = -1;}index++;}int res = 0;while (index < str.length()) {char c = str.charAt(index);if (c >= '0' && c <= '9') {int num = c - '0';if (res > Integer.MAX_VALUE / 10) {return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;} else if (res == Integer.MAX_VALUE / 10) {if (sign == -1 && num > 8) {return Integer.MIN_VALUE;} else if (sign == 1 && num > 7) {return Integer.MAX_VALUE;}} res = res * 10 + num;} else {return res * sign;}index++;}return res * sign;} }?
三刷:
寫多了也就順了。還是要多寫
Java:
Time Complexity - O(n), ?Space Complexity - O(1)
?
public class Solution {public int myAtoi(String str) {if (str == null || str.length() == 0) return 0;str = str.trim();int index = 0;boolean isNeg = false;if (str.charAt(index) == '-') {isNeg = true;index++;} else if (str.charAt(index) == '+') {index++;}int res = 0;while (index < str.length()) {char c = str.charAt(index);if (c > '9' || c < '0') return isNeg ? -res : res;if (res > Integer.MAX_VALUE / 10) {return isNeg ? Integer.MIN_VALUE : Integer.MAX_VALUE;} else if (res == Integer.MAX_VALUE / 10) {if (isNeg && (c - '0') > 8) return Integer.MIN_VALUE;else if (!isNeg && (c - '0') > 7) return Integer.MAX_VALUE;}res = res * 10 + c - '0';index++;}return isNeg ? -res : res;} }?
?
?
?
Python:
?
Reference:
?
轉載于:https://www.cnblogs.com/yrbbest/p/4430375.html
總結
以上是生活随笔為你收集整理的8. String to Integer (atoi)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网贷一般催收多久
- 下一篇: {面试题6: 重建二叉树}