165. Compare Version Numbers

Source: Internet
Author: User

First, the topic

1, examining

  

2. Analysis

Gives two non-empty version numbers that contain only numbers and dots, and compares the size of the version number.

Second, the answer

1, Ideas:

Method One,

①, split the string to cut the array, in order to compare the string in two arrays;

②, the short version number of the default is 0, continue to compare;

     Public intcompareversion (String version1, String version2) {string[] arr1= Version1.split ("\ \");//to cut a string with "."string[] arr2 = version2.split ("\ \.")); intLength =Math.max (Arr1.length, arr2.length);  for(inti = 0; i < length; i++) {Integer v1= i < arr1.length? Integer.parseint (Arr1[i]): 0; Integer v2= i < arr2.length? Integer.parseint (Arr2[i]): 0; intCompare =V1.compareto (v2); if(Compare! = 0)                returnCompare; }        return0; }

Method Two,

①, divides each "." into a number string into integers, sequentially comparing two strings;

②, the short version number of the default is 0;

     Public intcompareversion (String version1, String version2) {Integer tmp1= 0, TMP2 = 0; intLen1 = Version1.length (), len2 =version2.length (); inti = 0, j = 0;  while(I < Len1 | | J <len2) {TMP1= 0; TMP2= 0;  while(I < len1 && Version1.charat (i)! = '. ') Tmp1= TMP1 * + (Version1.charat (i++)-' 0 ');  while(J < Len2 && Version2.charat (j)! = '. ') TMP2= TMP2 * + (Version2.charat (j + +)-' 0 '); intCompare =Tmp1.compareto (TMP2); if(Compare! = 0)                returnCompare; I++;//skip "."J + +; }        return0; }

165. 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.