Help him
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1829 Accepted Submission(s): 137
Problem Description
As you know, when you want to hack someone's program, you must submit your test data. However sometimes you will submit invalid data, so we need a data checker to check your data. Now small W has prepared a problem for BC, but he is too busy to write the data checker. Please help him to write a data check which judges whether the input is an integer ranged from a to b (inclusive). Note: a string represents a valid integer when it follows below rules. 1. When it represents a non-negative integer, it contains only digits without leading zeros. 2. When it represents a negative integer, it contains exact one negative sign ('-') followed by digits without leading zeros and there are no characters before '-'. 3. Otherwise it is not a valid integer.
Input
Multi test cases (about 100), every case occupies two lines, the first line contain a string which represents the input string, then second line contains a and b separated by space. Process to the end of file. Length of string is no more than 100. The string may contain any characters other than '\n','\r'. -1000000000 ≤a≤b≤1000000000
Output
For each case output "YES" (without quote) when the string is an integer ranged from a to b, otherwise output "NO" (without quote).
Sample Input
10 -100 100 1a0 -100 100
Sample Output
YES NO
题意:
判断给你的字符串转换成数字时是否合法,并且数字大小要在[a,b]范围内。
分析:
一开始写了一大堆,判断各种不合法的情况,而且可能还有转义字符,所以写到最后还是WA。。。后来发现其实有一种非常简单的想法:只需把字符串先转换成数字,用itoa函数或者sprintf函数转换,由于如果出现不合法的字符出现时转换就会停止(例如:-10a54,中间的a是不合法的,所以这个字符串在被转换成数字时会是-10. ),然后再把这个数字转换成字符串,最后比较这个字符串和它所给的字符串是否相等,并且在[a,b]范围内,如果是的话就输出YES,否则输出NO。
结论:想法很重要!!!
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int a, b;
char m[110], c[110];
while(gets(m))
{
scanf("%d%d", &a,&b);
getchar();
int x = atoi(m);
sprintf(c, "%d", x);
//itoa(x,c,10);
if(strcmp(m,c) == 0 && x >=a && x <= b) puts("YES");
else puts("NO");
}
return 0;
}