[Java] Leetcode165 Compare Version Numbers

Source: Internet
Author: User

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

Assume that the version strings is non-empty and contain only digits and the.Character.
The.Character does not represent a decimal point and was used to separate number sequences.
For instance,2.5is not "both and a half" or "half-to-version three", it is the fifth Second-level revision of the second first-level re Vision.

Here are an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37

Test instructions is: Compare the size of the version number, assuming that the version number contains only numbers and decimal points. The first thing you might think of is the conversion of a character to an integer comparison size, but there can be multiple decimal points in the version number, which does not fit. Then think of using the split () method, the decimal point as a delimiter, divided into a character array, and then compare each.

The code is as follows:

public int Compareversion (string version1, String version2) {        string[] ver1=version1.split ("\ \.");        String[] Ver2=version2.split ("\ \");        int len1=ver1.length;        int len2=ver2.length;        int len=0;        if (len2<=len1) len=len2;        else Len=len1;        int num1=0;        int num2=0;        int i=0;        while (I<len)        {           num1=integer.valueof (ver1[i]);           Num2=integer.valueof (Ver2[i]);           if (num1==num2) i++;           else if (num1<num2) return-1;           else return 1;        }        while (len1>i)//There are decimal points, but the value after the decimal point is 0, not 0 returns 1, 0 is the return 0.        {          if (integer.valueof (ver1[i++])!=0) return 1;        }        I=len;        while (Len2>i)        {           if (integer.valueof (ver2[i++])!=0) return-1;          }        return 0;    }


[Java] Leetcode165 Compare Version Numbers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.