1+ // 165.✅ Compare Version Numbers
2+
3+ class Solution
4+ {
5+ public:
6+ int compareVersion (string version1, string version2)
7+ {
8+
9+ int i = 0 , j = 0 , n1 = version1.length (), n2 = version2.length (), num1 = 0 , num2 = 0 ;
10+
11+ while (i < n1 || j < n2)
12+ {
13+ while (i < n1 && version1[i] != ' .' )
14+ {
15+ // converting version1[i] to int for comparison
16+ num1 = num1 * 10 + (version1[i] - ' 0' );
17+ ++i;
18+ }
19+ while (j < n2 && version2[j] != ' .' )
20+ {
21+ // converting version2[i] to int for comparison
22+ num2 = num2 * 10 + (version2[j] - ' 0' );
23+ ++j;
24+ }
25+
26+ // acc to ques if version1 > version2 return 1;
27+ if (num1 > num2)
28+ return 1 ;
29+ // acc to ques if version1 < version2 return 1;
30+ if (num1 < num2)
31+ return -1 ;
32+
33+ ++i, ++j; // for the case when version[i] == '.' , we will skip that
34+ // If a version number does not specify a revision at an index,
35+ // then we have to treat the revision as 0
36+ num1 = 0 , num2 = 0 ;
37+ }
38+ return 0 ;
39+ }
40+ };
41+
42+ // correction need to be done stoi()
43+ class Solution
44+ {
45+ public:
46+ string split (string str)
47+ {
48+ string s1;
49+ for (auto i : str)
50+ {
51+ if (i != ' .' )
52+ s1.push_back (i);
53+ }
54+ return s1;
55+ }
56+
57+ int compareVersion (string version1, string version2)
58+ {
59+
60+ // spliting string from .
61+ string s1 = split (version1);
62+ string s2 = split (version2);
63+
64+ int mx = max (s1.length (), s2.length ());
65+ for (int i = 0 ; i < mx; ++i)
66+ {
67+ char c1 = s1[i];
68+ char c2 = s2[i];
69+ int v1 = i < s1.length () ? stoi (c1) : 0 ;
70+ int v2 = i < s2.length () ? stoi (c2) : 0 ;
71+
72+ if (v1 > v2)
73+ return 1 ;
74+ else if (v1 < v2)
75+ return -1 ;
76+ }
77+ return 0 ;
78+ }
79+ };
0 commit comments