Title: |
Compare Version Numbers |
Pass Rate: |
14.8% |
Difficulty: |
Simple |
Compare numbers version1 and version1.
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
I have seen this problem for a long time did not see, I feel that the topic is not described clearly, did not say that the version number may be multi-level such as said: 1.1.1.1 or 4.0.1.1 Such an example to give me to think that all is
x.x this kind of. I went to see someone else's code before I knew what it meant. I guess I understand the problem, right?
For two strings, first use "." For the Shard operation, the length can be judged when the Shard is finished. With two string length of the value as a cyclic condition, (just beginning I use a short to deal with, if there are 1.1 and 1 of the problem also to deal with the following value, too troublesome, directly with the long judgment, if the cross-border with 0 to fill) for you to compare if there are different immediately return, Returns 0 if the same is true after the loop condition has ended. The code is as follows:
1 Public classSolution {2 Public intcompareversion (String version1, String version2) {3 if(version1==NULL|| version2==NULL)return0;4String [] str1=version1.split ("\ \.")); 5String [] str2=version2.split ("\ \."));6 intlen1=str1.length;7 intLen2=str2.length;8 intLen=len1>len2?Len1:len2;9 for(inti=0;i<len;i++){Ten intnum1= i<len1? Integer.parseint (Str1[i]): 0; One intNum2= i<len2? Integer.parseint (Str2[i]): 0; A if(NUM1>NUM2)return1; - if(NUM1<NUM2)return-1; - } the return0; - - } -}
Leetcode------Compare Version Numbers