题解 | #c++ 这个题较难?? 9 行搞定,还可以优化 #

把字符串转换成整数

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

/*首先,这个题不考虑字母*/
/*那就简单多了,只考虑数字,遇到其他情况直接返回-1就行了*/
class Solution {
public:
    int StrToInt(string str) {
        int ans = 0;int isplus = 1;
        for(char ch:str){
            if(isalpha(ch)){
                return 0;
            }if (ch == '+' || ch =='-'){
                isplus = (ch == '+') ? 1 : -1; 
            }if(isdigit(ch)){
                ans = ans*10+ch-'0';
            }
        }return isplus*ans;
    }
};
全部评论
这个代码有问题,如果是“12&23”这种,特殊字符在中间就不符合了,只是这道题目测试案例没有给这种
1 回复 分享
发布于 2023-08-13 12:05 广东
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; } }; 这样才万无一失
1 回复 分享
发布于 2023-08-13 12:16 广东

相关推荐

MingoTree:看不出你你的技术栈,想找什么工作,然后课设项目别写上去了,自我评价删了,前后端你想好你要干啥,这种简历投上去秒挂的
点赞 评论 收藏
分享
评论
7
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务