标签:
No.165 Compare Version Numbers
Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the .
character.
The .
character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5
is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
Here is an example of version numbers ordering: 0.1 < 1.1 < 1.2 < 13.37
比较版本数字的大小:
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. 题意其实很简单,就是比较自定义的由‘.‘分隔的版本数字的大小 0.1 < 1.1 < 1.2 < 13.37
方法: 从前到后依次取由‘.‘分隔的数字进行比较,若小,返回-1;若大,返回1;若等于,比较下一级
最后,全部等于,才返回0
别想的太复杂,思路其实类似atoi(),可以简化自己写,就不要过于依赖函数
1 class Solution 2 { 3 public: 4 //假设:1.2 < 1.2.1 5 //疑问:只有.怎么办? 6 int compareVersion(string version1, string version2) 7 {//从头到尾依次比较,以.为分隔符 8 //别想的太复杂,思路其实类似atoi(),可以简化自己写,就不要过于依赖函数 9 if(version1.size()==0 && version2.size() == 0) 10 return 0; 11 12 auto it1 = version1.begin(); 13 auto it2 = version2.begin(); 14 int data1 = 0; 15 int data2 = 0; 16 17 while(it1 != version1.end() || it2!= version2.end())//将&&变为||,就不需要单独再考虑了!!! 18 { 19 data1=0; 20 while(it1 != version1.end() && (*it1) != ‘.‘) 21 { 22 data1 = data1*10 + (*it1)-‘0‘;//居然漏了-‘0‘ 23 it1++; 24 } 25 data2=0; 26 while(it2 != version2.end() && (*it2) != ‘.‘) 27 { 28 data2 = data2*10 + (*it2)-‘0‘; 29 it2++; 30 } 31 if(data1 > data2) 32 return 1; 33 if(data1 < data2) 34 return -1; 35 //否则,进行下一轮比较 36 if(it1 != version1.end()) 37 it1++;//跳过.号 38 if(it2 != version2.end()) 39 it2++;//跳过.号 40 } 41 // if(it1 != version1.end()) 42 // return 1; 43 // if(it2 != version2.end()) 44 // return -1; 45 46 return 0; 47 } 48 };
另外,可参考[LeetCode] Compare Version Numbers,其思路更加清晰。
No.165 Compare Version Numbers
标签:
原文地址:http://www.cnblogs.com/dreamrun/p/4543973.html