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

把字符串转换成整数

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

class Solution 
{
public:
    int StrToInt(string str) 
    {
        int result= 0 ; 
        int flag =1 ;
         for(auto ch : str)
         {
              //有字母
           if( isalpha(ch) ) //Check if character is alphabetic
           {
            return 0 ;
           }
           // + 不影响结果
           if(ch =='+' || ch == '-'  )
           {
            flag = ch=='+' ? 1 : -1;
           }
           //数字
           if(isdigit(ch))
           {
           result = result *10 + ch-'0';//将字符转换为整数,并且结果向左移动一位
           }
         }
         return flag * result;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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