8. String to Integer (atoi) 字符串转成整数
[抄題]:
Input: "42" Output: 42Example 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.?[暴力解法]:
時間分析:
空間分析:
?[優化后]:
時間分析:
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
[思維問題]:
根本不知道應該怎么處理越界啊:
先設置一個bound變量,-2147483648/10。當前num > bound || num == bond & digit > 7都不行
?
[英文數據結構或算法,為什么不用別的數據結構或算法]:
[一句話思路]:
寫整齊點,要考慮到的問題:空格(用trim)、符號(用標記變量)、越界
[輸入量]:空:?正常情況:特大:特小:程序里處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫圖]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
? [五分鐘肉眼debug的結果]:
[總結]:
?digit是最后一位數,不用新相乘
[復雜度]:Time complexity: O(n) Space complexity: O(1)
[算法思想:迭代/遞歸/分治/貪心]:
[關鍵模板化代碼]:
[其他解法]:
[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?
轉載于:https://www.cnblogs.com/immiao0319/p/9383582.html
總結
以上是生活随笔為你收集整理的8. String to Integer (atoi) 字符串转成整数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【React自制全家桶】一、Webstr
- 下一篇: python爬虫必会的23个项目