Validate an IP Address

PROBLEM :

Write a program to Validate an IPv4 Address. Your task is  to complete the function isValid which returns 1 if the ip address is valid else returns 0. The function takes a string ip as its only argument .

Input:
The first line of each test case contains an integer T denoting the number of test case . Then T test cases follow . Each test case takes a string ip.

Output:
For each test case output will be 1 if the string is a valid ip address else 0.

Constraints:
1<=T<=50
1<=length of string <=50

Example(To be used only for expected output) :

Input
2
222.111.111.111
5555..555

Output
1
0

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/* The function returns 1 if
IP string is valid else return 0
You are required to complete this method */

bool check(char *,int ,int ) ;
int isValid(char *ip)
{
   int beg,end ;
   beg=0 ;
   end=0 ;
 
   int len,i,no ;
   len=strlen(ip) ;
   no=0 ;
 
   for(i=0;i<len;i++)
   {
        if(ip[i]!='.')
            end++ ;
        else
        {
            no++ ;
            if(!check(ip,beg,end))
                return 0 ;
            beg=i+1 ;
            end=i+1 ;
        }
   }
   if(no!=3)
        return 0 ;
 
   return 1 ;
}

bool check(char *ip,int beg,int end)
{
    if(end<=beg)
        return 0 ;
       
    while(beg!=end)
    {
        if(!((ip[beg]>='0')&&(ip[beg]<='9')))
            return 0 ;
        beg++ ;
    }
    return 1 ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )