LG P5238 整数校验器

题目描述

有些时候需要解决这样一类问题:判断一个数\(x\)是否合法.
\(x\)合法当且仅当其满足如下条件:

  • \(x\)格式合法,一个格式合法的整数要么是\(0\),要么由一个可加可不加的负号,一个\(1\)\(9\)之间的数字,和若干个\(0\)\(9\)之间的数字依次连接而成.
  • \(x\)在区间\([l,r]\)范围内(即\(l \le x \le r\)).

你需要实现这样一个校验器,对于给定的\(l, r\),多次判断\(x\)是否合法.

分析

先来水一发python题解

l,r,T=map(int, input().split())

for i in range(T):
    s=input()
    if(s== "-"):
        print("1")
        continue
    n=int(s)
    if(str(n)!=s):
        print("1")
    else:
        if(n>=l and n<=r):
            print("0")
        else:
            print("2")

以下是正解:

按照题意模拟即可。

注意到格式不合法会有如下情况:

  • \(-\)
  • \(-0\dots\)
  • \(0\dots\)

特判掉不合法后,先根据位数判断是否在long long范围内(可能仍然会爆long long,使用unsigned long long存储),然后再判断大小即可.

Code

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cctype>
#include <sstream>

using namespace std;

const int Maxn=1e6+5;
typedef long long LL;

inline LL Input()
{
    register LL x=0;
    register int s=1,c=getchar();

    while(c<'0'||c>'9')
        (c=='-')&&(s=-1),
        c=getchar();

    while(c>='0'&&c<='9')
		x=(x<<3)+(x<<1)+(c^48),
                c=getchar();

    return x*s;
}

LL l,r;
int t;
char ch[Maxn];

int main()
{
    l=Input(),r=Input(),t=Input();

    while (t--)
    {
        scanf("%s",ch+1);
        int len=strlen(ch+1);

        if(ch[1]=='-')
        {
            if(ch[2]=='0'||len==1)
            {
                puts("1");
                continue;
            }
        }
        else if(ch[1]=='0'&&len!=1)
        {
            puts("1");
            continue;
        }
        else if(ch[1]=='-'&&len>20)
        {
            puts("2");
            continue;
        }
        else if(ch[1]!='-'&&len>19)
        {
            puts("2");
            continue;
        }

        unsigned LL tmp=0;
        LL x=0;

        if(ch[1]=='-')
        {
            sscanf(ch+2,"%llu",&tmp);
            if(tmp>(1LL<<63))
            {
                puts("2");
                continue;
            }
            x=-tmp;
        }
        else
        {
            sscanf(ch+1,"%llu",&tmp);

            if(tmp>=(1LL<<63))
            {
                puts("2");
                continue;
            }

            x=tmp;
        }

        puts(x>=l&&x<=r?"0":"2");
    }
}
posted @ 2019-08-12 15:48  Anverking  阅读(214)  评论(0编辑  收藏  举报