atoi实现(考虑足够多种的情况)c++
生活随笔
收集整理的這篇文章主要介紹了
atoi实现(考虑足够多种的情况)c++
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
簡(jiǎn)述
在leetcode上遇到這個(gè)問題,還以為很簡(jiǎn)單,結(jié)果遇到了很多坑。
但總的來說,這個(gè)版本的atoi應(yīng)該是實(shí)現(xiàn)中最為完整的版本了吧(有問題的話后續(xù)再補(bǔ)充)。
假設(shè)我們的環(huán)境只能存儲(chǔ) 32 位大小的有符號(hào)整數(shù),那么其數(shù)值范圍為 [?231, 231 ? 1]。如果數(shù)值超過這個(gè)范圍,請(qǐng)返回 INT_MAX (231 ? 1) 或 INT_MIN (?231) 。
錯(cuò)誤實(shí)例
實(shí)現(xiàn)的代碼需要符合下面的這幾個(gè)條件
1. "-5-" 應(yīng)該輸出 -5 2. "0-1" 應(yīng)該輸出 0 3. "-2147483648" 應(yīng)該輸出 -2147483648 4. "+-2" 應(yīng)該輸出 0 5. "42" 應(yīng)該輸出 42 6. " -42" 應(yīng)該輸出 -42 7. "4193 with words" 應(yīng)該輸出 4193 8. "words and 987" 應(yīng)該輸出 0 9. "-91283472332" 應(yīng)該輸出 -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;} };總結(jié)
以上是生活随笔為你收集整理的atoi实现(考虑足够多种的情况)c++的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 区间重合--c++
- 下一篇: 有序数组给定始末的中位数c++