题解 | #把字符串转换成整数#

把字符串转换成整数

https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e

#include <cstddef>
// class Solution {
//   public:
//     int StrToInt(string str) {
//         for (size_t i = 0 ; i < str.size(); i++)
//         {
//             首位情况特殊处理
//            if ((str[0] == '+' || str[0] == '-') || (str[i] >= '1' && str[i] <='9'))
//            {
//             int flag = 1;
//             int num = 0;
//             if (str[0] == '-') {
//                 flag = -1;
//             }
//             size_t len = str.size();
//             for (size_t i = 0; i < len; i++)
//             {
//                 if (str[i] >= '1' && str[i] <= '9') {
//                     num += (str[i] - '0') * int(pow(10, len - 1 - i));
//                 }
//                 else if(str[0] != '+' && str[0] != '-')
//                 {
//                    return 0;
//                 }
//             }
//             return flag * num;
//            }
//         }
//         return 0;
//     }
// };

class Solution {
  public:
    int StrToInt(string str) {
        int ans = 0;
        int isplus = 1;
        for (char ch : str) {

            if (ch == '+' || ch == '-') {
                isplus = (ch == '+') ? 1 : -1;
            } else {
                if (ch < '1' || ch > '9') {
                    return 0;
                } else {
                    ans = ans * 10 + ch - '0';
                }
            }
        }
        return isplus * ans;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务