String to Integer (atoi)

 

实现atoi这个函数,将一个字符串转换为整数。如果没有合法的整数,返回0。如果整数超出了32位整数的范围,返回INT_MAX(2147483647)如果是正整数,或者INT_MIN(-2147483648)如果是负整数。

您在真实的面试中是否遇到过这个题?  是

题目纠错

样例

"10" =>10

"-1" => -1

"123123123123123" => 2147483647

"1.0" => 1

 要注意的方面:正负号,小数点,是否溢出。

  • 所用到的函数:
    • string:erase()
    • // string::erase
      #include <iostream>
      #include <string>
      
      int main ()
      {
        std::string str ("This is an example sentence.");
        std::cout << str << '\n';
                                                 // "This is an example sentence."
        str.erase (10,8);                        //            ^^^^^^^^
        std::cout << str << '\n';
                                                 // "This is an sentence."
        str.erase (str.begin()+9);               //           ^
        std::cout << str << '\n';
                                                 // "This is a sentence."
        str.erase (str.begin()+5, str.end()-9);  //       ^^^^^
        std::cout << str << '\n';
                                                 // "This sentence."
        return 0;
      }

      string:find_first_not_of()

    • // string::find_last_not_of
      #include <iostream>       // std::cout
      #include <string>         // std::string
      #include <cstddef>        // std::size_t
      
      int main ()
      {
        std::string str ("Please, erase trailing white-spaces   \n");
        std::string whitespaces (" \t\f\v\n\r");
      
        std::size_t found = str.find_last_not_of(whitespaces);
        if (found!=std::string::npos)
          str.erase(found+1);
        else
          str.clear();            // str is all whitespace
      
        std::cout << '[' << str << "]\n";
      
        return 0;
      }

       

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值