题解 | #IP地址#

IP地址

https://www.nowcoder.com/practice/2359e23180194f99828f5cd9c764236a

#include <stdio.h>
int isIplegal(int ipNum,int ipBits);
int main() {
    char ipAd[16]="";
    int ipNum,ipBits,dotCount,isLegal;
  while(scanf("%s",ipAd)!=EOF){
    ipNum=0,ipBits=0,dotCount=0,isLegal=1;
    if(ipAd[15]!='\0'||ipAd[8]=='\0')//ip长度不合法
    {
        printf("No!\n");
        continue;
    }
    for(int i=0;ipAd[i]!='\0';i++)
    {
        if(ipAd[i]<'0'||ipAd[i]>'9')
        {
            if(ipAd[i]=='.')
            {
                dotCount++;
                if(isIplegal(ipNum,ipBits)==0)
                {
                    isLegal=0;
                    break;
                }
                ipNum=ipBits=0;
            }
            else {
                isLegal=0;
                break;
            }
        }

        else if(ipAd[i]=='0')
        {
            ipBits++;
            if(ipAd[i+1]!='\0'&&ipAd[i+1]!='.'&&ipBits==1)
            {
                isLegal=0;
                break;
            }
        }
        else{
            ipBits++;
            ipNum=ipNum*10+(ipAd[i]-'0'); 
        }
    }
    if(dotCount!=3)
        isLegal=0;
    if(isIplegal(ipNum,ipBits)==0)
        isLegal=0;
    if(isLegal==0)
        printf("No!\n");
    else
        printf("Yes!\n");
  }
    return 0;
   
}

int isIplegal(int ipNum,int ipBits)
{
    if(ipNum<0||ipNum>255||ipBits<0||ipBits>3)
        return 0;
    else
        return 1;
}

全部评论

相关推荐

09-28 09:18
吉首大学 Java
离上岸不远了的牛油很...:同27,你写的专业技能那些是真熟练了吗,我感觉稍微问深一点我都要🐔
你找实习最大的坎坷是什么
点赞 评论 收藏
分享
10-17 23:18
已编辑
西北农林科技大学 Web前端
独行m:给25可以试试,但他只能给12,那就是纯纯的事精
秋招,不懂就问
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务