leetcode--Compare Version Numbers

来源:互联网 发布:hbo 知乎 编辑:程序博客网 时间:2024/06/11 07:15

Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37
[java] view plain copy
  1. public class Solution {  
  2.     public int compareVersion(String version1, String version2) {  
  3.         String[] v1 = version1.split("\\.");  
  4.         String[] v2 = version2.split("\\.");          
  5.         int i = 0;  
  6.         while(i<v1.length&&i<v2.length){  
  7.             int p = Integer.parseInt(v1[i]);              
  8.             int q = Integer.parseInt(v2[i]);  
  9.             if(p>q){  
  10.                 return 1;  
  11.             }else if(p<q){  
  12.                 return -1;  
  13.             }  
  14.             i++;  
  15.         }  
  16.         if(i==v1.length){  
  17.             if(i==v2.length){  
  18.                 return 0;  
  19.             }else{  
  20.                 while(i<v2.length){  
  21.                     if(Integer.parseInt(v2[i])>0){                         
  22.                         return -1;                        
  23.                     }  
  24.                     i++;  
  25.                 }  
  26.                 return 0;  
  27.             }             
  28.         }else{  
  29.             while(i<v1.length){  
  30.                 if(Integer.parseInt(v1[i])>0){  
  31.                     return 1;                     
  32.                 }  
  33.                 i++;  
  34.             }  
  35.             return 0;             
  36.         }  
  37.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46388059

原创粉丝点击