In this HackerEarth Sahil's computer address problem solution we have Given a String S, you need to report if the given String is a valid IP Address :

A valid IP address is:
  1. It has exactly 4 non-empty parts separated by 3 dots, like: 255 [dot] 255 [dot] 255 [dot] 255
  2. The decimal value of each part of the IP address should never exceed 255 and never be less than zero.
[dot] is written, instead of the .(dot) character for readability.


HackerEarth Sahil's computer address problem solution


HackerEarth Sahil's computer address problem solution.

#include<bits/stdc++.h>
using namespace std;

int main()
{
int dots = 0, i = 0;
string s, octet_str;
cin >> s;

bool is_valid = true;
while (1)
{
char c = s[i++];
if (c == '.' || c == 0)
{
if (octet_str.empty())
{
is_valid = false;
break;
}

int octet_value = stoi(octet_str);
if (octet_value < 0 || octet_value > 255)
{
is_valid = false;
break;
}

if (c == 0)
break;

++dots;
octet_str.clear();
}
else
{
octet_str += c;
}
}

if (dots != 3)
{
is_valid = false;
}

cout << (is_valid ? "YES\n" : "NO\n");
return 0;
}