leetcode---Compare Version Numbers

来源:互联网 发布:linux磁盘阵列 编辑:程序博客网 时间:2024/05/16 06:04

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

解题思路:要使用切分,逐一比较,需要注意的是使用循环来实现进位以及如何找到分隔符,数字。
下面的代码是leetcode的最快的代码,抄来的。。。。。

public class Solution {    public int compareVersion(String version1, String version2) {        int l1=version1.length();        int l2=version2.length();        int i=0,j=0,v1=0,v2=0;        while(i<l1||j<l2){            while(i<l1&&version1.charAt(i)!='.'){                v1=10*v1+(version1.charAt(i)-'0');                i++;            }            while(j<l2&&version2.charAt(j)!='.'){                v2=10*v2+(version2.charAt(j)-'0');                j++;            }            if(v1>v2) return 1;            else if(v1<v2) return -1;            else{                v1=0;v2=0;                i++;j++;            }        }        return 0;    }}
0 0