时间限制:1 秒
内存限制:128 兆
特殊判题:否
提交:104
解决:30
-
题目描述:
-
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。
-
输入:
-
输入可能包含多个测试样例。
对于每个测试案例,输入为一个合法或者非法的字符串,代表一个整数n(1<= n<=10000000)。
-
输出:
-
对应每个测试案例,
若输入为一个合法的字符串(即代表一个整数),则输出这个整数。
若输入为一个非法的字符串,则输出“My God”。
-
样例输入:
-
5 -5 +8
-
样例输出:
-
5 -5 8
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
char s[20];
while(scanf("%s", s) == 1)
{
if(strlen(s) == 1)
{
if(isdigit(s[0]))
printf("%c\n", s[0]);
else printf("My God\n");
continue;
}
int ffFlag = 0;
for(int i = 1; s[i]; i++)
if(!isdigit(s[i]))
ffFlag = 1;
if(ffFlag == 0)
{
if(s[0] != '+' && s[0] != '-' && !isdigit(s[0]))
printf("My God\n");
else if(s[0] == '+')
printf("%s\n", s + 1);
else printf("%s\n", s);
}
else printf("My God\n");
}
return 0;
}
/**************************************************************
Problem: 1508
User: true14fans
Language: C
Result: Accepted
Time:0 ms
Memory:912 kb
****************************************************************/
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
char s[100];
while(scanf("%s", s) == 1)
{
int n = strlen(s), res = 0, fifaFlag = 0;
if(n == 1)
{
if(isdigit(s[0]))
{
printf("%d\n", s[0] - '0');
continue;
}
else
{
printf("My God\n");
continue;
}
}
if(s[0] == '-')
{
for(int i = 1; i < n; i++)
{
if(!isdigit(s[i]))
{
printf("My God\n");
fifaFlag = 1;
break;
}
res = res * 10 + s[i] - '0';
}
if(fifaFlag == 0)
printf("%d\n", -1*res);
}
else if(isdigit(s[0]))
{
res = s[0] - '0';
for(int i = 1; i < n; i++)
{
if(!isdigit(s[i]))
{
printf("My God\n");
fifaFlag = 1;
break;
}
res = res * 10 + s[i] - '0';
}
if(fifaFlag == 0)
printf("%d\n", res);
}else if(s[0] == '+')
{
for(int i = 1; i < n; i++)
{
if(!isdigit(s[i]))
{
printf("My God\n");
fifaFlag = 1;
break;
}
res = res * 10 + s[i] - '0';
}
if(fifaFlag == 0)
printf("%d\n", res);
}else
printf("My God\n");
}
return 0;
}