atoi实现(考虑足够多种的情况)c++
生活随笔
收集整理的這篇文章主要介紹了
atoi实现(考虑足够多种的情况)c++
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡述
在leetcode上遇到這個問題,還以為很簡單,結果遇到了很多坑。
但總的來說,這個版本的atoi應該是實現中最為完整的版本了吧(有問題的話后續再補充)。
假設我們的環境只能存儲 32 位大小的有符號整數,那么其數值范圍為 [?231, 231 ? 1]。如果數值超過這個范圍,請返回 INT_MAX (231 ? 1) 或 INT_MIN (?231) 。
錯誤實例
實現的代碼需要符合下面的這幾個條件
1. "-5-" 應該輸出 -5 2. "0-1" 應該輸出 0 3. "-2147483648" 應該輸出 -2147483648 4. "+-2" 應該輸出 0 5. "42" 應該輸出 42 6. " -42" 應該輸出 -42 7. "4193 with words" 應該輸出 4193 8. "words and 987" 應該輸出 0 9. "-91283472332" 應該輸出 -2147483648代碼
class Solution { public:bool isdigit(char c) {return c <= '9' && c >= '0';}int myAtoi(string str) {bool pos = true,check=false;int ans = 0, i;for(i = 0; i < str.size(); ++i){if (str[i] == ' ') continue;if (str[i] != '+' && str[i] != '-' && ! isdigit(str[i])) return 0;break;}for(; i < str.size(); ++i){if (isdigit(str[i])) {if (pos && ans == 214748364 && str[i] >= '7') return 2147483647;if (pos && ans > 214748364) return 2147483647;if (!pos && ans == 214748364 && str[i] >= '8') return -2147483648;if (!pos && ans > 214748364) return -2147483648;ans *= 10;ans += str[i] - '0';check = true;}else if (!check && str[i] == '+') {pos = true; check = true;}else if (!check && str[i] == '-') {pos = false; check = true;}else if (check && (str[i] == '+' || str[i] == '-') && ans == 0) return 0;else break;}return pos? ans:-ans;} };總結
以上是生活随笔為你收集整理的atoi实现(考虑足够多种的情况)c++的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 区间重合--c++
- 下一篇: 有序数组给定始末的中位数c++