Validate an IP Address | Practice | GeeksforGeeks

Write a program to Validate an IPv4 Address.
According to Wikipedia, IPv4 addresses are canonically 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 .
A valid IPv4 Address is of the form x1.x2.x3.x4 where 0 <= (x1, x2, x3, x4) <= 255.
Thus, we can write the generalized form of an IPv4 address as (0-255).(0-255).(0-255).(0-255).
Note: Here we are considering numbers only from 0 to 255 and any additional leading zeroes will be considered invalid.
Your task is to complete the function isValid which returns 1 if the given IPv4 address is valid else returns 0. The function takes the IPv4 address as the only argument in the form of string.
Example 1:
Input:
IPv4 address = 222.111.111.111
Output: 1
Explanation: Here, the IPv4 address is as
per the criteria mentioned and also all
four decimal numbers lies in the mentioned
range.


Example 2:
Input:
IPv4 address = 5555..555
Output: 0
Explanation: 5555..555 is not a valid
IPv4 address, as the middle two portions
are missing.
Your Task:
Complete the function isValid() which takes the address in the form of string s as an input parameter and returns 1 if this is a valid address otherwise returns 0.
Expected Time Complexity: O(N), N = length of the string.
Expected Auxiliary Space: O(1)

Constraints:
1<=length of string <=50

Note: The Input/Output format and Example given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
mukesh kumar3 days ago
class Solution {   public:       int isValid(string s) {           if(s.size() < 7)  //minimum lenght of ip address 0.0.0.0   return 0;  //check for minimum and maximum three dots  size_t _count = std::count(s.begin(), s.end(), '.');  if( _count != 3)   return 0;  string tmpStr(s);  string currVal;  int currValInt;  int pos;  while(_count > 0)  {   pos = tmpStr.find('.');   currVal = tmpStr.substr(0, pos);   if(!isdigit(currVal[0]))        //to check a.b.c.d       return 0;   currValInt = stoi(currVal);             if(currValInt == 0 && currVal.size()>1)     //000.000.000.000       break;          if(currVal.size() > 3)                      //3343.46546.323.11    break;       if(currValInt > 255 || currValInt < 0 )         //300.333.266.32    break;      if((currValInt < pow(10,currVal.length()-1)) && (currValInt != 0))      //01.022.22.44          return 0;   tmpStr = tmpStr.substr(pos + 1);   _count--;  }  if(_count > 0)   return 0;  //Now validate the last element of the IP address i.e. out of x1.x2.x3.x4 validate x4  currValInt = stoi(tmpStr);  if(currValInt == 0 && tmpStr.size() > 1)      return 0;  if(tmpStr.size() == 0 || tmpStr.size() > 3)   return 0;  if(stoi(tmpStr) > 255 || stoi(tmpStr) < 0 )   return 0;  if((currValInt < pow(10,tmpStr.length()-1)) && (currValInt != 0))      return 0;  return 1;       }};
0
nitishmishra9371 week ago
    public boolean isValid(String s) {       // Write your code here       StringBuilder b = new StringBuilder();       int subCount = 0;       int dotCount = 0;       /*if(s.equals("00.00.00.00") || s.equals("000.000.000.000")) {           return false;       }*/       for(int i = 0; i < s.length(); ++i) {           if(s.charAt(i) == '.') {               if(dotCount > 3) {                   return false;               }               ++dotCount;               try {               Integer num = Integer.valueOf(b.toString());               if(num > -1 && num < 256) {                       subCount = 0;                       b.setLength(0);                      } else {                       return false;                   }               } catch (NumberFormatException e) {                   return false;               }           } else {               ++subCount;               if(subCount > 3) {                   return false;               } else {                   if(b.length() != 0 && b.toString().equals("0")) {                       return false;                   }                   b.append(s.charAt(i));               }           }       }       return dotCount == 3;   }
0
ayushmahobia011 week ago
 int isValid(string s) {           // code here               int count = 0;   for (int i = 0; i < s.length(); i++)   {       if (s[i] == '.')       {           count++;       }   }   if (count != 3)       return 0;
   unordered_set<string> st;   for (int i = 0; i < 256; i++)   {       st.insert(to_string(i));   }
   count = 0;   string temp = "";   for (int i = 0; i < s.length(); i++)   {       if (s[i] != '.')       {           temp += s[i];       }       else       {           if (st.count(temp) != 0)           {               count++;           }           temp = "";       }   }   if (st.count(temp) != 0)   {       count++;   }   if (count == 4)       return 1;   else       return 0;       }
0
wajid945711 week ago
// good question
 
class Solution {  private:  int solve(string str, char sep){      string temp = "";      int c=0;      int count=0;       for(int i=0; i<str.length(); i++){          if(str[i] !=sep){            temp += str[i];            if(temp.size()>3|| temp=="00" || ((temp[0]>='a' && temp[0]<='z') || (temp[0]>='A' && temp[0]<='Z')) ){                return 0;            }          }         else{             c++;                    if(temp.size()==0  || (temp.size()>=2 && temp[0]=='0')|| temp.size()>3){                 return 0;             }             if(stoi(temp)<0 || stoi(temp)>255){                return 0;              }              temp = "";          }      }         for(int i=0;i<str.size();i++){             if(str[i]=='.'){                 count++;             }         }         if(count>3){             return 0;         }
      if(stoi(temp)<0 || stoi(temp)>255 || (temp.size()>=2 && temp[0]=='0')){                return 0;      }
      if(c<3 || c>3){        return 0;      }            return 1;  }  public:  int isValid(string s) {      return solve(s,'.');  }};
+1
kartikeyashokgautam1 week ago
Easy JAVA Solution :-
 
  public boolean isValid(String s) {         int count = 0;              for(int i=0;i<s.length();i++)       {           if(s.charAt(i)=='.') count++;              }              if(count!=3) return false;
       HashSet<String> hs = new HashSet<>();              for(int i=0;i<256;i++)       {           hs.add(Integer.toString(i));       }              count = 0;               String temp = "";              for(int i=0;i<s.length();i++)       {           if(s.charAt(i)!='.')           {               temp+= s.charAt(i);           }                      else           {               if(hs.contains(temp))               {                   count++;               }                              temp = "";           }                  }               if(hs.contains(temp))               {                   count++;               }              if(count == 4)       {           return true;       }       return false;
   }
-1
roshan852k1 week ago
class Solution {   private:   int solve(string str, char sep){       string temp = "";       int c=0;         for(int i=0; i<str.length(); i++){           if(str[i] !=sep){           temp += str[i];           }          else{              c++;              if(stoi(temp)<0 || stoi(temp)>255){                 return 0;               }               temp = "";           }       }              if(stoi(temp)<0 || stoi(temp)>255){                 return 0;       }              if(c<3){         return 0;       }              return 1;   }   public:   int isValid(string s) {           // code here       return solve(s,'.');   }};
+2
jack11432 weeks ago
Executed in 0.01sec
class Solution {
    public:
        int isValid(string s) {
            // code here
            int i = 0, count = 0;
            while(i < s.size()){
                string tmp;
                while(i < s.size() and s[i] != '.' and s[i] >= '0' and s[i] <= '9')tmp += s[i++]; //only accepting integer
                if(tmp.size() == 0 || tmp.size() > 3 || stoi(tmp) > 255 || stoi(tmp) < 0)return 0; // valid number checking
                if(tmp.size() >= 2 and tmp[0] == '0')return 0; //chekcing leading zeros;
                if(s[i] == '.')count++;
                i++;
            }
            if(count < 3 || count > 3)return 0; //checking 32bit
            return 1;
        }
0
sumitsinghrajput786gwalior2 weeks ago
//completed in java
class Solution {
   public boolean isValid(String s) {       // Write your code here       if(s.compareTo("")==0){           return false;       }       if(s.length()<7)return false;       int dot = 0;       for(int i=0;i<s.length();i++){           if('.' == s.charAt(i)){               dot++;           }       }       if(dot!=3)return false;       String S = s.replace(".","@");        String[] str = S.split("@");       if(str.length != 4){           return false;       }       boolean ans = true;       for(int i=0;i<4;i++){           if(str[i].length()<4){               try{                   int n = Integer.parseInt(str[i]);                   if(0<=n && n<=255){                       if(str[i].length()>1 && (n>=0 && n<=9))return false;                       continue;                   }                   else{                       return false;                   }               }               catch(Exception e){                   return false;               }           }           else{               return false;           }       }       return true;   }}
0
minipandey3322 weeks ago
//Anybody tells me what's wrong in below code.
int isValid(string s) {           // code here           int dot=0;                      int r=0;           for(int i=0; i<s.length(); i++) // 222.111.111.111           {                            if(s[i]>=0 && s[i] <= 9)               {                   int x = atoi(s[i]);                   r =  r*10 + x;                }                               else if(s[i] == '.')               {   dot++;                 if(r>255 || r<0)                  return 0;                                      r=0;                }                              else                return 0;           }           if(dot==3)           return 1;                      else            return 0;       }};
+1
dtu_top_coder2 weeks ago
1st Try Solution Accepted
C++ Code :
 
class Solution {   public:       int isValid(string s)        {           string str="";           int count=0;           s.push_back('.');                      for(int i=0;i<s.size();i++)           {               if(s[i]=='.')               {                   if(!check(str))                   return false;                                      str="";                   count++;               }                              else               {                   str+=s[i];               }           }                      if(count==4)           return true;                      return false;       }              bool check(string s)       {           if(s=="" || (s[0]=='0' && s.size()>1))           return false;                      int a=atoi(s.c_str());                      for(auto c:s)           if(c<'0' || c>'9')           return false;                      if(a>=0 && a<=255)           return true;                      return false;       }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.