Title:
Detailed description:
Implement the following interface:
Boolisipaddressvalid (constchar * pszipaddr)
Input: pszipaddr string
Output: valid IP addresses of true, invalid IP addresses of false
Constraints
The input IP address is in the format of XXX. XXX.
The two ends of the string contain spaces and are considered as legal IP addresses.
The string contains spaces and is considered as an invalid IP address.
Similar to 01.1.1.1, The 1.02.3.4 IP Sub-segment starts with 0 as an invalid IP Address
The sub-segment is a single 0, which is regarded as a valid IP address, and 0.0.0.0 is also a valid IP address.
C language code:
1 # include "ipaddressvalid. H "2 # include <string. h> 3 4 bool isipaddressvalid (const char * pszipaddr) 5 {6 // implement 7 if (pszipaddr = 0 | pszipaddr = ") 8 return false here; 9 char * P = const_cast <char *> (pszipaddr); 10 char * pre = 0; 11 bool flag = true; 12 bool last = false; 13 int pcount = 0; // point number; 14 int num = 0; 15 while (* P = '') // do not consider the preceding space: 16 P ++; 17 // If (* P = '. ') 18 // return false; 19 while (* P! = '\ 0') {20 if (* P! = '. ') {21 if (pcount <3 & (* P> '9' | * P <'0') 22 return false; 23 if (pcount = 3) {24 if (* P! = ''& (* P> '9' | * P <'0') // 25 return false; 26 if (* P = '') // The third '. 'There is a space behind it. It should be the Ending Space 27 last = true; 28 If (last & * P <= '9' & * P> = '0 ') 29 return false; 30} 31 if (FLAG) // The new child segment starts. 32 pre = P; 33 flag = false; 34} else {// found a "." 35 pcount ++; 36 IF (! Flag) {37 If (P-PRE> 1 & * pre = '0') | (p-PRE> 3 )) // exclude sub-segments starting with 0, or sub-segments with a length greater than 338 return false; 39 if (p-pre = 3) {40 num = (* pre-'0') * 100; 41 num + = (* (++ pre)-'0') * 10; 42 num + = (* (++ pre)-'0'); 43 44 If (Num> 255) 45 return false; 46} 47} else if (p-pre = 1) {// two consecutive '. '48 return false; 49} else50 return false; 51 flag = true; // The next sub-segment starts 52 pre = P; 53} 54 p ++; 55} 56 If (pcount! = 3 | * pre = '. '| (p-PRE> 1 & * pre = '0') // if it is not three child segments or the last character is '. ', or the first character of the last child segment is '0 '. 57 Return false; 58 num = 0; 59 While (* pre <= '9' & * PRE> = '0') {60 num = num * 10; 61 num = num + (pre [0]-'0'); 62 63 pre ++; 64} 65 if (Num> 255) 66 return false; 67 68 return true; 69}
Huawei OJ-judge whether the input string is a valid IP Address