imashutosh51

Compare Version Numbers

Feb 27th, 2026
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. """
  2. The idea is to split both version strings into lists of integers so each revision level can be compared numerically instead of lexicographically.
  3. We then iterate up to the maximum length of both lists, treating missing revision levels as 0, and return as soon as a difference is found; if no difference exists, the versions are equal.
  4. """
  5. class Solution:
  6.     def compareVersion(self, version1: str, version2: str) -> int:
  7.         v1 = list(map(int, version1.split('.')))
  8.         v2 = list(map(int, version2.split('.')))
  9.        
  10.         n = max(len(v1), len(v2))
  11.        
  12.         for i in range(n):
  13.             num1 = v1[i] if i < len(v1) else 0
  14.             num2 = v2[i] if i < len(v2) else 0
  15.            
  16.             if num1 > num2:
  17.                 return 1
  18.             elif num1 < num2:
  19.                 return -1
  20.        
  21.         return 0
Advertisement
Add Comment
Please, Sign In to add comment