Leetcode (-compare) Version Numbers

Source: Internet
Author: User

Topic:
CompareversionNumbers version1 andVersion2. If version1 > Version2return 1,ifVersion1 < Version2return-1, otherwisereturn 0.Assume that  the versionStrings is Non-empty and containOnly digits and  the.character. The.character does  notRepresent a decimal point and  isUsed toSeparate NumberSequences. For instance,2.5  is  not "Both and a half" or "Half to version three",it  is  the Fifth Second-level Revision of  the Second  First-level revision. Here isAn example of versionNumbers Ordering:0.1<1.1<1.2<13.37
Ideas:
    • Test instructions: Comparing the size of two version number strings
    • Convert the string to an array with split, pay attention to split (\.), and then convert to an integer, traversing the comparison. Note If the version number is followed by a zero condition
Code:
 Public classSolution { Public int compareversion(String version1, String version2) {string[] v1,v2;if(Version1.indexof (".") == -1) {V1 =Newstring[1]; v1[0] = Version1; }Else{V1 =NewString[version1.split ("\\."). length]; V1 = Version1.split ("\\."); }if(Version2.indexof (".") == -1) {v2 =Newstring[1]; v2[0] = Version2; }Else{v2 =NewString[version2.split ("\\."). length]; V2 = Version2.split ("\\."); }int[] array1 = Stoint (v1);int[] array2 = Stoint (v2);intnn = math.min (array1.length,array2.length); for(intA =0; a < nn;a++) {if(Array1[a] > Array2[a]) {return 1; }Else if(Array1[a] < Array2[a]) {return-1; }        }if(Array1.length > Array2.length) { for(intK = nn; K < array1.length;k++) {if(Array1[k]! =0){return 1; }            }return 0; }Else if(Array1.length < Array2.length) { for(intm = nn;m < array2.length;m++) {if(Array2[m]! =0){return-1; }            }return 0; }return 0; } Public int[]Stoint(string[] ss) {intn = ss.length;int[] result =New int[n]; for(inti =0; i < n;i++) {Try{Result[i] = Integer.parseint (Ss[i]); }Catch(Exception e) {            }        }returnResult }}

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.