日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

8. String to Integer (atoi)

發布時間:2025/5/22 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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: 二刷思路就比較清晰。依然是有下面幾個步驟:

  • 判斷str是否為空或者長度是否為0
  • 處理前部的space,也可以用str = str.trim();
  • 嘗試求出符號sign
  • 定義結果int res = 0 , ?處理數字
  • 假如char c = str.charAt(index)是數字,則定義int num = c - '0', 接下來判斷是否越界
  • 當前 res > Integer.MAX_VALUE / 10,越界,根據sign 返回 Integer.MAX_VALUE或者 Integer.MIN_VALUE
  • res == Integer.MAX_VALUE / 10時, 根據最后sign和最后一位數字來決定是否越界,返回Integer.MAX_VALUE或者 Integer.MIN_VALUE
  • 不越界情況下,res = res * 10 + num
  • 否則返回當前 res * sign
  • 返回結果 res * sign
  • 這里比較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)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。