Microsoft Interview Question
Software Engineer / Developersbool check_ip(char * IP)
{
//char IP[16] = "255.255.255.255";
if(strlen(IP) > 16)
return false;
char * range = strtok(IP, ".");
short c = 0;
while ((range != 0) && (c < 4)) {
if((strlen(range) <= 3) && (atoi(range) >= 0) && (atoi(range) <= 255)) ++c;
else break;
range = strtok(0, ".");
}
return (c == 4);
}
static bool IsValidIpAddress( string address )
{
if (address == null)
return false;
string[] numbers = address.Split('.');
if (numbers.Length != 3)
return false;
foreach (string current in numbers)
{
int num = 0;
if (!int.TryParse(current, out num))
return false;
if (num < 0 || num > 255)
return false;
}
return true;
}
not sure if atoi does error handling like Integer.valueof(String s)...
I mean ...atoi("3j4")...you will not get any exception...
so we need to check that all the 3 chars are valid digits...maybe that time also check permissible digit values for each char...like 0-2...0-5...0-5...small optimization
bool verifyIP(char* ip)
- Jackie September 12, 2008{
int ippartN=0;
int count=0;
//be in the form of 255.255.255.255
//1.read one char, a.test whether it is digit: if yes, concat it to the string variable;if no, return 0;
//2.when reaching an ".", end composing the string variable, convert it to an integer and test wehther it is between 0-255, if yes, continue with next step, if no, return 0
//3.if the string is a numberic string between 0-255, increase the count with 1
//4.continue step 1-3 till end of the string
//5.test whether count=4, if yes, return 1, otherwise return 0;
char current=0;
char prechar=0;
if(!ip) return 0;
while(*ip)
{
current=*ip;
if(current=='.')
{
if(prechar==current)
return 0;
ippartN=0;
count++;
prechar=current;
if(count>4) return 0;
ip++;
continue;
}
else{
if((current<'0')||(current>'9'))
return 0;
ippartN=ippartN*10+current-'0';
prechar=current;
}
ip++;
}
if((ippartN<0)||(ippartN>255))
return 0;
count++;
if(count==4) return 1;
return 0;
}