剑指Offer字符串转换成整数

版权声明:所有的博客都是博主的个人笔记。。。。。 https://blog.csdn.net/qq_35976351/article/details/83380011

题目描述

将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

思路

注意合法性判别即可

AC代码

class Solution {
  public:
    int StrToInt(string str) {
        if(str.empty()) {
            return 0;
        } else if((str[0] < '0' || str[0] > '9') && str[0] != '+' && str[0] != '-') {  // 第一个不是合法的符号
            return 0;
        } else if((str[0] == '+' || str[0] == '-') && str.length() == 1) {  // 仅仅输入符号的情况
            return 0;
        } else if(str[0] > '0' && str[0] < '9') {  // 无符号
            for(int i = 0; i < str.length(); ++i) {  // 合法性判别
                if(str[i] < '0' || str[i] > '9') {
                    return 0;
                }
            }
        }
        int res = 0;
        int n = 1;
        bool tag = false;
        for(int i = str.length() - 1; i >= 0; --i) {
            if(str[i] == '-') {
                tag = true;
                break;
            } else if(str[i] == '+') {
                break;
            }
            res += (str[i] - '0') * n;
            n *= 10;
        }
        if(tag)
            res = -res;
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_35976351/article/details/83380011