알고리즘/codefights

21>isIPv4Address

Diademata 2017. 7. 4. 16:42
반응형

An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.


IPv4 addresses are represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1.


Given a string, find out if it satisfies the IPv4 address naming rules.


Example


For inputString = "172.16.254.1", the output should be

isIPv4Address(inputString) = true;


For inputString = "172.316.254.1", the output should be

isIPv4Address(inputString) = false.


316 is not in range [0, 255].


For inputString = ".254.255.0", the output should be

isIPv4Address(inputString) = false.


There is no first number.


code>>


bool isIPv4Address(std::string inputString) {


std::string tok;

std::stringstream ss(inputString);

int count = 0;

while (getline(ss, tok, '.'))

{

if (tok.size() == 0) return false;

for (int i = 0; i < tok.size(); i++)if (!isdigit(tok[i])) return false;

if (!(atoi(tok.c_str()) >= 0 && atoi(tok.c_str()) <= 255)) return false;

count++;

}

if (count != 4) return false;

    return true;

}


정규표현식 사용 한 것들 보니 놀랍다. ㅋㅋ


regex_match는 정규 표현식과 문자열이 정확하게 일치해야 참을 반환


다른 사람 풀이>>


bool isIPv4Address(std::string s) {

    regex r("[0-9]{1,3}(.[0-9]{1,3}){3}");

    if(!regex_match(s,r))return false;

    int a,b,c,d;

    sscanf(s.c_str(),"%d.%d.%d.%d", &a,&b,&c,&d);

    return a<256 && b<256 && c<256 && d<256;

}


bool isIPv4Address(std::string inputString) {
    regex r("^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}$");
    smatch m;
    return regex_match(inputString, m, r);
}


반응형

'알고리즘 > codefights' 카테고리의 다른 글

23>boxBlur  (0) 2017.07.05
22>avoidObstacles  (0) 2017.07.05
20>arrayMaximalAdjacentDifference  (0) 2017.07.04
19>areEquallyStrong  (0) 2017.07.02
18>palindromeRearranging  (0) 2017.07.02