Help him
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 480 Accepted Submission(s): 119
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.
Length of string is no more than 100.
The string may contain any characters other than '\n','\r'.
-1000000000$\leq a \leq b \leq 1000000000$
題解及代碼:
題意很簡單,給一個字符串,和一個區間,看這個字符串能否構成一個合法的整數,並且其值是否在這個區間內(注意-0爲非法數據)。
首先直接排除-和-0的情況,然後判斷前導0的情況,再判斷0-9以外字符的情況,接着看其長度是否大於12,最後把它轉化成整數,判斷大小。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
typedef long long ll;
bool judge(char s[],ll a,ll b)
{
ll num=0,d=1,i=0;
int len=strlen(s),k=0;
if(s[0]=='-') d=-1,k++;
if(k==len||s[0]=='-'&&s[k]=='0') return false;
for(i=k;i<len-1;i++)
if(s[i]!='0') break;
if(i!=k) return false;
for(int i=k;i<len;i++)
if(s[i]<'0'||s[i]>'9') return false;
for(int i=k;i<len;i++)
{
num=num*10+s[i]-'0';
if(i-k>11) return false;
}
//printf("%I64d\n",num*d);
if(num*d<a||num*d>b) return false;
return true;
}
int main()
{
ll a,b;
char s[110];
while(gets(s)!=NULL)
{
scanf("%I64d%I64d",&a,&b);
if(a>b) swap(a,b);
if(judge(s,a,b)) printf("YES\n");
else printf("NO\n");
getchar();
}
return 0;
}