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