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

从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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值