Medium
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.
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.
Input/Output
-
[execution time limit] 0.5 seconds (c)
-
[input] string inputString
A string consisting of digits, full stops and lowercase English letters.
Guaranteed constraints:
1 ≤ inputString.length ≤ 30. -
[output] boolean
- true if inputString satisfies the IPv4 address naming rules, false otherwise.
[C] Syntax Tips
// Prints help message to the console
// Returns a string
char * helloWorld(char * name) {
char * answer = malloc(strlen(name) + 8);
printf("This prints to the console when you Run Tests");
strcpy(answer, "Hello, ");
strcat(answer, name);
return answer;
}
Solution
bool isIPv4Address(char *inputString)
{
int dotCount=0, N=0;
for(int i=0;i<strlen(inputString);i++)
{
if(!isdigit(inputString[i]) && inputString[i]!='.')
return false;
if(isdigit(inputString[i]))
{
N*=10;
N+=inputString[i]-'0';
if(N==0 && inputString[i]=='0' && inputString[i+1]!='.' && i!=strlen(inputString)-1)
return false;
if(N>255)
return false;
}
if(inputString[i]=='.')
{
dotCount++;
if(!isdigit(inputString[i-1]) || i==0 || N>255)
return false;
N=0;
}
if(i==strlen(inputString)-1 && inputString[i]=='.')
return false;
}
return dotCount==3 && N<256;
}
'Codesignal' 카테고리의 다른 글
<Codesignal> Box Blur (0) | 2020.04.05 |
---|---|
<Codesignal> avoidObstacles (0) | 2020.04.05 |
<Codesignal> arrayMaximalAdjacentDifference (0) | 2020.04.05 |
<Codesignal> areEquallyStrong (0) | 2020.04.05 |
<Codesignal> palindromeRearranging (0) | 2020.04.05 |