Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between 0 and 255, inclusive.
Input to the function is guaranteed to be a single string. Print 1 if addr is a valid IP address, Print 0 otherwise.
1.2.3.4
123.45.67.89
1.2.3
1.2.3.4.5
123.456.78.90
123.045.067.089
输入
Input to the function is guaranteed to be a single string.
输出
Print 1 if addr is a valid IP address, Print 0 otherwise.
样例
标准输入 复制文本 |
1.2.3.4 |
标准输出 复制文本 |
1 |
标准输入 复制文本 |
1.2.3.4.5 |
标准输出 复制文本 |
0 |
标准输入 复制文本 |
44.544.1201.089 |
标准输出 复制文本 |
0 |
提示
they consist of four octets->4*8=32位 1111 1111(二进制)=255(十进制)故范围0~255
思路:
1.char a[100];
2.scanf("%s",a);
3.sscanf(a,"%d.%d.%d.%d%n",&n[0],&n[1],&n[2],&n[3], &nc)!= 4 //判断是否是4组
4.使用strstr(a,".0")判断并排除10.012.1.1这类不合法IP
5.用循环判断数组n的值是否在0~255范围内