题解 | #合法IP#

合法IP

https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9

#include <stdio.h>
#include<string.h>


int main() {
    char str[15] = {0};
    gets(str);
    int pos[3] = {0}; //存放点位置
    int n = 0; //点数量
    int d=0;
	for(int i=0;i<strlen(str);i++){
		if(46==str[i]){
			pos[n]=i;
			if(n>0){
				d=i-pos[n-1];
			}
			n++;
			if(1==d){
                break;
            }
		}
	}
	if(3!=n||0==pos[0]||strlen(str)-1==pos[2]||1==d||(str[0]=='0'&&str[1]!='.')||(str[pos[0]+1]=='0'&&str[pos[0]+2]!='.')||(str[pos[1]+1]=='0'&&str[pos[1]+2]!='.')||(str[pos[2]+1]=='0'&&str[pos[2]+2]!=0)){
		printf("NO\n");
		return 0;
	}
    int num[4] = {0};
    int x = 1;
    for (int i = pos[0] - 1; i > -1; i--) {
        num[0] += (str[i] - 48) * x;
        x = x * 10;
    }
    x = 1;
    for (int i = pos[1] - 1; i > pos[0]; i--) {
        num[1] += (str[i] - 48) * x;
        x = x * 10;
    }
    x = 1;
    for (int i = pos[2] - 1; i > pos[1]; i--) {
        num[2] += (str[i] - 48) * x;
        x = x * 10;
    }
    x = 1;
    for (int i = strlen(str) - 1; i > pos[2]; i--) {
        num[3] += (str[i] - 48) * x;
        x = x * 10;
    }

    int key = 1;
    for (int i = 0; i < 4; i++) {
        if (num[i] > 255 || num[i] < 0) {
            key = 0;
        }
    }

    if (1 == key) {
        printf("YES\n");
    } else {
        printf("NO\n");
    }


    return 0;
}

这个题缝缝补补半天,终于通过了。

全部评论

相关推荐

uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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