九度OJ1508:把字符串转换成整数

来源:互联网 发布:月薪2万 知乎 编辑:程序博客网 时间:2024/06/06 02:44

题目链接:http://ac.jobdu.com/problem.php?pid=1508

分析:题目要求将一个数字字符串转换成整数。需要考虑到以下情况:

1. 字符串开始的空串;

2. 正负号的处理;

3. 数字串中含有非法字符,此时为非法,不必继续处理。

tip:更复杂的情况,该数字串表示的为float或double类型的数据。

C++实现:

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <cstring>#include <vector>#include <string>#include <stack>#include <algorithm>using namespace std;char str[10000005];void process(char str[]){int len = strlen(str);int res = 0;int i = 0;while(str[i] == ' ' && i < len) i ++;bool tag = false;if(str[i] == '-'){tag = true;i ++;}if(str[i] == '+') i ++;bool flag = false;while(i < len){if(str[i] < '0' || str[i] > '9'){flag = true;break;}res = res * 10 + (str[i] - '0');i ++;}if(flag){printf("My God\n");return;}if(tag){res = -res;}printf("%d\n", res);}void input(){while(scanf("%s", str) != EOF){process(str);}}int main(){input();return 0;}


0 0