[windows C/C++]面试准备(一)字符串类面试题2

来源:互联网 发布:安徽农村高考知乎 编辑:程序博客网 时间:2024/06/06 15:19

从3个方面准备面试:

1. 字符串类题目(完成例题)

2.多线程面试题

3.C++语法相关的题目

1.字符串类题目

1.3 字符串转换成整数

实现一个atoi,首先查看atoi文档。
需要注意的地方有:首位可能有1个符号,中间可能有若干个空格,可能含有非法字符(数字以外的ascii,字母、标点等),可能会超出INT_MAX,INT_MIN。
/*题目:输入一个由数字组成的字符串,把它转换成整数并输出。例如:输入字符串"123",输出整数123。给定函数原型int StrToInt(const char *str) ,实现字符串转换成整数的功能,不能使用库函数atoi。思路:*/#include <iostream>#include <string>#include <cstring>using namespace std;int StrToInt(const char *str) {int num = 0;int sign = 1;int len = strlen(str);if (str == NULL) return 0;int pos = 0;while (str[pos] == ' ' && pos < len) ++pos;if (str[pos] == '+' || str[pos] == '-') {if (str[pos] == '-')sign = -1;++pos;}for (; pos < len; ++pos) {if (str[pos] < '0' || str[pos] > '9')break;if (num > INT_MAX / 10 || (num == INT_MAX / 10 && (str[pos] - '0') > INT_MAX % 10))return sign == -1 ? INT_MIN : INT_MAX;num = num * 10 + str[pos] - '0';}return num * sign;}int main() {string str1 = "1234490";string str2 = "0";cout << str1 << " => " << StrToInt(str1.c_str()) << endl;cout << str2 << " => " << StrToInt(str2.c_str()) << endl;system("pause");return 0;}


0 0