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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

8. String to Integer (atoi) 字符串转成整数

發(fā)布時間:2025/4/9 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 8. String to Integer (atoi) 字符串转成整数 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

[抄題]:

Input: "42" Output: 42

Example 2:

Input: " -42" Output: -42 Explanation: The first non-whitespace character is '-', which is the minus sign.Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words" Output: 4193 Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987" Output: 0 Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332" Output: -2147483648 Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.Thefore INT_MIN (?231) is returned.

?[暴力解法]:

時間分析:

空間分析:

?[優(yōu)化后]:

時間分析:

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

[思維問題]:

根本不知道應(yīng)該怎么處理越界啊:

先設(shè)置一個bound變量,-2147483648/10。當前num > bound || num == bond & digit > 7都不行

?

[英文數(shù)據(jù)結(jié)構(gòu)或算法,為什么不用別的數(shù)據(jù)結(jié)構(gòu)或算法]:

[一句話思路]:

寫整齊點,要考慮到的問題:空格(用trim)、符號(用標記變量)、越界

[輸入量]:空:?正常情況:特大:特小:程序里處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

[一刷]:

  • 注意要把string轉(zhuǎn)成字符才能操作
  • 字符不是統(tǒng)一處理的 在符號處理和越界處理之后,都要再分別進行i++
  • [二刷]:

  • 整數(shù)的范圍是 ‘0’? <= c <= '9',必須有等號
  • [三刷]:

  • ?num的進位方式是 num = num * 10 + digit digit是最后一位數(shù),不用新相乘
  • [四刷]:

    [五刷]:

    ? [五分鐘肉眼debug的結(jié)果]:

    [總結(jié)]:

    ?digit是最后一位數(shù),不用新相乘

    [復雜度]:Time complexity: O(n) Space complexity: O(1)

    [算法思想:迭代/遞歸/分治/貪心]:

    [關(guān)鍵模板化代碼]:

    [其他解法]:

    [Follow Up]:

    [LC給出的題目變變變]:

    ?[代碼風格] :

    ?[是否頭一次寫此類driver funcion的代碼] :

    ?[潛臺詞] :

    ?

    class Solution {public int myAtoi(String str) {//handle spacestr = str.trim();int i = 0;char[] c = str.toCharArray();//signsint sign = 1;if (i < c.length && (c[i] == '+' || c[i] == '-')) {if (c[i] == '-') sign = -1;i++;}//out of bound in two waysint bound = Integer.MAX_VALUE / 10;int num = 0;while (i < c.length && (c[i] >= '0' && c[i] <= '9')){int digit = c[i] - '0';//out of boundif (num > bound || (num == bound && digit > 7)) {//depend on signreturn (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;}num = digit + num * 10;i++;}return num * sign;} } View Code

    ?

    轉(zhuǎn)載于:https://www.cnblogs.com/immiao0319/p/9383582.html

    總結(jié)

    以上是生活随笔為你收集整理的8. String to Integer (atoi) 字符串转成整数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。