Leetcode 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, was not "both and 2.5 a half" or "half-to-version three", it is the fifth Second-level revision of the S Econd first-level revision.

Here are an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37
Problem Solving Ideas:

General idea, split string with split (), Important:some special characters need to being escaped while providing them a deli Miters like "." and "\".

Then use Integer.parseint (x) to convert to an int comparison size. Note: 1.0 and 1 are equal, so when you have one string left, the value is either equal to 0 or greater than the other string.

The problem is not difficult, but easy to be wrong, careful carefully.

Java Code:

 Public intcompareversion (String version1, String version2) {string delimiter= "\\."; string[] V1=Version1.split (delimiter); String[] V2=Version2.split (delimiter); intLen =Math.max (V1.length, v2.length);  for(inti = 0; i< Len; i++){            if(I < v1.length && I <v2.length) {                if(Integer.parseint (V1[i]) >Integer.parseint (V2[i])) {                    return1; }Else if(Integer.parseint (V1[i]) <Integer.parseint (V2[i])) {                    return-1; }            }Else if(I <v1.length) {if(Integer.parseint (v1[i]) > 0) {                    return1; }            }Else if(I <v2.length) {                if(Integer.parseint (v2[i]) > 0) {                    return-1; }            }        }        return0; }

Reference:

1. http://www.programcreek.com/2014/03/leetcode-compare-version-numbers-java/

Leetcode Compare Version Numbers

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.