Compare two Version numbers | C / C ++ program to compare two version number ; Method to compare two versions . Returns 1 if v2 is smaller , - 1 if v1 is smaller , 0 if equal ; vnum stores each numeric part of version ; loop until both string are processed ; storing numeric part of version 1 in vnum1 ; storing numeric part of version 2 in vnum2 ; if equal , reset variables and go for next numeric part ; Driver method to check above comparison function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int versionCompare ( string v1 , string v2 ) { int vnum1 = 0 , vnum2 = 0 ; for ( int i = 0 , j = 0 ; ( i < v1 . length ( ) || j < v2 . length ( ) ) ; ) { while ( i < v1 . length ( ) && v1 [ i ] != ' . ' ) { vnum1 = vnum1 * 10 + ( v1 [ i ] - '0' ) ; i ++ ; } while ( j < v2 . length ( ) && v2 [ j ] != ' . ' ) { vnum2 = vnum2 * 10 + ( v2 [ j ] - '0' ) ; j ++ ; } if ( vnum1 > vnum2 ) return 1 ; if ( vnum2 > vnum1 ) return -1 ; vnum1 = vnum2 = 0 ; i ++ ; j ++ ; } return 0 ; } int main ( ) { string version1 = "1.0.3" ; string version2 = "1.0.7" ; if ( versionCompare ( version1 , version2 ) < 0 ) cout << version1 << " ▁ is ▁ smaller STRNEWLINE " ; else if ( versionCompare ( version1 , version2 ) > 0 ) cout << version2 << " ▁ is ▁ smaller STRNEWLINE " ; else cout << " Both ▁ version ▁ are ▁ equal STRNEWLINE " ; return 0 ; }