File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* ************************************************************************
2
+
3
+
4
+ Write a program to Validate an IPv4 Address.
5
+
6
+ According to Wikipedia, IPv4 addresses are canonically represented in
7
+ dot-decimal notation, which consists of four decimal numbers,
8
+ each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1 .
9
+
10
+
11
+ The generalized form of an IPv4 address is (0-255).(0-255).(0-255).(0-255).
12
+ Here we are considering numbers only from 0 to 255 and
13
+ any additional leading zeroes will be considered invalid.
14
+
15
+ Your task is to complete the function isValid which returns 1,
16
+ if the ip address is valid else returns 0.
17
+
18
+ The function takes a string s as its only argument .
19
+
20
+ **************************************************************************/
21
+
22
+
23
+ SOLUTION (in C++):
24
+
25
+ #include < bits/stdc++.h>
26
+
27
+ using namesapce std;
28
+
29
+ int isValid (string s)
30
+ {
31
+ s += ' .' ;
32
+ int countDots = 0 ;
33
+ string str = " " ;
34
+ for (int i = 0 ;i<s.length ();i++)
35
+ {
36
+ if (s[i] != ' .' )
37
+ {
38
+ if (s[i] >= 48 && s[i] <= 57 )
39
+ str += s[i];
40
+ else
41
+ return 0 ;
42
+ }
43
+ if (s[i] == ' .' )
44
+ {
45
+ if (str[0 ] == ' .' && str.length () > 1 )
46
+ return 0 ;
47
+ stringstream obj (str);
48
+ int x = 0 ;
49
+ obj>>x;
50
+ if (x<0 || x>255 )
51
+ return 0 ;
52
+ if (str.size () == 0 )
53
+ return 0 ;
54
+ countDots++;
55
+ str = " " ;
56
+ }
57
+ if (countDots == 4 )
58
+ return 1 ;
59
+ else
60
+ return 0 ;
61
+ }
62
+
63
+
64
+ int main ()
65
+ {
66
+ string s;
67
+ cin>>s;
68
+ int k = isValid (s);
69
+ if (k == 0 )
70
+ cout<<" Valid" <<endl;
71
+ else
72
+ cout<<" Not Valid" <<endl;
73
+ return 0 ;
74
+ }
You can’t perform that action at this time.
0 commit comments