LeetCode 8. String to Integer (atoi)

https://leetcode.com/problems/string-to-integer-atoi/description/

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.

  • 字符串简单题,主要是注意细节,看定义里时如何处理输入字符串的。判断不规则但是有效输入,无效格式,溢出数据。处理溢出数据时,要注意判断条件。
  • 判断溢出时需要注意 abs(INT_MIN) (-2147483648) > abs(INT_MAX) (2147483647)。
  • 两种解法思想一样,就是第一种用了isdigit()判断数字,更简洁。
  • atoi - C++ Reference
    • http://www.cplusplus.com/reference/cstdlib/atoi/
  • isdigit - C++ Reference
    • http://www.cplusplus.com/reference/cctype/isdigit/
  1 //
  2 //  main.cpp
  3 //  LeetCode
  4 //
  5 //  Created by Hao on 2017/3/16.
  6 //  Copyright © 2017年 Hao. All rights reserved.
  7 //
  8 
  9 #include <iostream>
 10 #include <cstring>
 11 #include <vector>
 12 using namespace std;
 13 
 14 class Solution {
 15 public:
 16     int myAtoi(string str) {
 17         int i = 0;
 18         int result = 0;
 19         
 20         if (str.empty()) return 0;
 21         
 22         while (' ' == str.at(i) && i < str.size()) ++ i;
 23         
 24         if (i == str.size()) return 0;
 25         
 26         int sign = 1;
 27         
 28         if ('+' == str.at(i)) {
 29             sign = 1;
 30             ++ i;
 31         } else if ('-' == str.at(i)) {
 32             sign = -1;
 33             ++ i;
 34         }
 35         
 36         while (i < str.size() && isdigit(str.at(i))) {       // isdigit() from <cctype>
 37             if (result > (INT_MAX - (str.at(i) - '0')) / 10) // use > instead of >= for that abs(INT_MIN) (-2147483648) > abs(INT_MAX) (2147483647)
 38                 return -1 == sign ? INT_MIN : INT_MAX;
 39             
 40             result = result * 10 + (str.at(i) - '0');
 41             
 42             ++ i;
 43         }
 44         
 45         return result * sign;
 46     }
 47     
 48     int myAtoi2(string str) {
 49         int num = 0;
 50         int sign = 1;
 51         int i = 0;
 52         const int n = str.length();
 53         
 54         if (n == 0) return 0;
 55         
 56         while ((str[i] == ' ') && (i < n))
 57             i ++;
 58         
 59         if (str[i] == '+')
 60             i ++;
 61         else if (str[i] == '-') {
 62             sign = -1;
 63             i ++;
 64         }
 65         
 66         while (i < n) {
 67             if (str[i] < '0' || str[i] > '9')
 68                 break;
 69             
 70             // Be careful for out of range value
 71             if ((num > INT_MAX / 10) || ((num == INT_MAX / 10) && ((str[i] - '0') > INT_MAX % 10)))
 72                 return sign == -1 ? INT_MIN : INT_MAX;
 73             
 74             num = num * 10 + (str[i] - '0');
 75             
 76             i ++;
 77         }
 78         
 79         return num * sign;
 80     }
 81 };
 82 
 83 int main(int argc, char* argv[])
 84 {
 85     Solution    testSolution;
 86     string      result;
 87     
 88     vector<string> sVec = {"      -11919730356x", "", "1", "-2147483648", "-2147483647", "2147483647", "2147483648", "-3924x8fc", "+ 413", "++c", " ++1", "+413"};
 89     
 90     /*
 91      -2147483648
 92      0
 93      1
 94      -2147483648
 95      -2147483647
 96      2147483647
 97      2147483647
 98      -3924
 99      0
100      0
101      0
102      413
103      */
104     for (auto s : sVec) {
105         cout << testSolution.myAtoi(s) << endl;
106         cout << testSolution.myAtoi2(s) << endl;
107     }
108 
109     return 0;
110 }
View Code

 

 

转载于:https://www.cnblogs.com/pegasus923/p/7449544.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值