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.255.255.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.
Example:
Input: 255.255.255.0
Output: YES
Approach
C++
#include <bits/stdc++.h>using namespace std;void computerAddress(string s){int n = s.size();int i = 0;int flag = 0;int cnt = 0;while (i < n){string str = "";while (i < n && s[i] != '.'){str += s[i];i++;}cnt++;if (cnt > 4){flag = 1;break;}stringstream geek(str);int x = 0;geek >> x;if (x > 255){flag = 1;break;}i++;}if (i == n + 1 && flag == 0)cout << "YES\n";elsecout << "NO\n";}int main(){string s = "255.255.255.0";computerAddress(s);return 0;}
No comments:
Post a Comment