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

把字符串转换成整数

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;
    }
};

全部评论

相关推荐

驼瑞驰_招募评论官版...:反正我信了,上牛客,拿offer
腾讯开奖372人在聊
点赞 评论 收藏
分享
站队站对牛:兄弟 你这是四年就当大一过了吧 也许你校园卡 赚了有五位数了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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