[Huawei machine trial exercise] 5. IP address determination validity, Huawei 5.ip
Question
Determines whether the input string is a valid IP address.
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.
Knowledge Point: String
Source: 111
Exercise stage: Intermediate
Code
/* ------------------------------------- * Date: 2015-06-25 * Author: SJF0115 * Subject: IP address determination validity * Source: Huawei machine license */# include <iostream >#include <cstring> using namespace std; bool isIPAddressValid (const char * pszIPAddr) {if (pszIPAddr = NULL) {return false;} // if int size = strlen (pszIPAddr ); // remove leading 0 int start = 0; while (pszIPAddr [start] = '') {+ + start;} // while // import 0 int en after Removal D = size-1; while (pszIPAddr [end] = '') {-- end;} // while int num = 0; int pointCount = 0; int first = start; for (int I = start; I <= end + 1; ++ I) {if (pszIPAddr [I]> = '0' & pszIPAddr [I] <= '9 ') {num = num * 10 + pszIPAddr [I]-'0';} // if else if (pszIPAddr [I] = '. '| I = end + 1) {if (I = start | (pszIPAddr [I-1] <'0' | pszIPAddr [I-1]> '9 ')) {return false;} // verify. count if (pszIPAddr [I] ='. ') {++ PointCount; if (pointCount> 3) {return false;} // if // verify the data if (num> 255 | num <0) {return false;} // if // starts with 0 and is not 0. For example: 023 if (num! = 0 & pszIPAddr [first] = '0') {return false;} // if first = I + 1; num = 0 ;} // else {return false;} // else} // for if (pointCount! = 3) {return false;} return true ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.