日韩性视频-久久久蜜桃-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)的全部內容,希望文章能夠幫你解決所遇到的問題。

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

    主站蜘蛛池模板: 黑人极品ⅴideos精品欧美棵 | 一级免费视频 | 亚洲麻豆视频 | 欧美资源网 | 无码少妇一区二区三区芒果 | 欧美第五页 | 91免费小视频 | 伊人院| 麻豆久久久久久久久久 | 欧美极品少妇xxxxⅹ裸体艺术 | 视频一区中文字幕 | 最新网址av | 日韩在线视频免费 | 成人靠逼视频 | 亚洲 欧美 自拍偷拍 | 蜜臀99久久精品久久久久久软件 | 国产精品黄色大片 | 亚洲免费看片 | 男人天堂久久 | 国产va在线观看 | 一区二区导航 | 国产精品久久久久久三级 | 大吊一区二区三区 | 免费在线 | 日韩欧美中文字幕在线播放 | 精品视频一区在线观看 | 久久精品国产99精品国产亚洲性色 | 国产精品污网站 | 欧美一区二区三区不卡视频 | 美女被啪啪 | 日本老少交 | 中文字幕免费在线观看 | 国产一级爽片 | 亚洲va久久久噜噜噜久久天堂 | 欧美日韩亚洲二区 | 国产成人自拍网 | 欧美国产日韩在线视频 | 亚洲精品国产欧美 | 亚洲熟女一区二区三区 | av片免费在线播放 | 91爱爱·com| 亚洲少妇18p | 97在线播放| 人超碰 | 亚洲色图 在线视频 | 免费精品一区二区 | 国产免费一区二区三区四区五区 | 国精产品一区一区三区mba下载 | 国产精品一区二区三区免费 | 亚洲精品在线看 | 人人妻人人玩人人澡人人爽 | 人人艹在线观看 | 欧美性在线观看 | 久热精品免费视频 | 日韩免费网址 | 美女黄站 | 午夜伦理剧场 | 先锋影音男人 | 永久免费av无码网站性色av | 伊人网在线播放 | 91视频色| 国产无遮挡又黄又爽免费网站 | 在线观看国产三级 | 国产在线第二页 | 翔田千里一区 | 精品九九久久 | 日韩精品无码一区二区三区久久久 | 成人超碰在线 | h视频免费在线 | 国产精品1区 | 亚洲自拍偷拍欧美 | 精品探花 | 精品免费久久 | 99riav在线| 北条麻妃一区二区三区四区五区 | 狂野欧美性猛交xxxx777 | 前任攻略在线观看免费完整版 | 午夜小电影 | 涩涩视频网址 | 亚洲性视频在线 | 永久毛片| 天堂av一区| 久草免费在线观看 | 国产剧情自拍 | 色人天堂 | 免费在线观看中文字幕 | 日本公妇乱淫免费视频一区三区 | 人人澡人人澡 | 欧美精品一区二区三区三州 | 香蕉视频亚洲 | 91欧美亚洲| 黑丝一区| 欧美国产91 | 伊人网大 | 成人免费播放视频 | 久久第一页 | 九九热伊人 | 在线免费中文字幕 | 中文字幕av在线 |