HDU 2206 IP的计算

来源:互联网 发布:windows 搜索功能坏了 编辑:程序博客网 时间:2024/06/16 11:36

题意:IP地址由四部分组成,每个部分为8位,表示一个无符号整数,因此不需要正号的出现,IP地址中没有空格出现。判断输入的IP地址是否合法

解题思路:无符号整数的范围是0~255,用sscanf将IP地址读入到a,b,c,d中,同时判断a,b,c,d四个数字是否在0~255之间,再用a,b,c,d四个数字转换成一个合法的IP地址读入到一个新的字符串中,然后判断这两个字符串是否相同,相同则说明合法,否则就不合法

代码:

#include <iostream>#include <algorithm>#include <cstring>#include <string>#include <cmath>#include <cstdio>using namespace std;int main(){    char str[110],temp[110];    int a,b,c,d;    while(gets(str)!=NULL)    {        if(sscanf(str,"%d.%d.%d.%d",&a,&b,&c,&d)==4&&a>=0&&a<=255&&b>=0&&b<=255&&c>=0&&c<=255&&d>=0&&d<=255)        {            sprintf(temp,"%d.%d.%d.%d",a,b,c,d);//            cout<<a<<" "<<b<<" "<<c<<" "<<d<<"ggg"<<endl;//            cout<<str<<"fff"<<endl;//            cout<<temp<<"hhh"<<endl;            if(strcmp(temp,str)==0)            {                printf("YES\n");            }            else printf("NO\n");        }        else printf("NO\n");    }    return 0;}


原创粉丝点击