Compare Version Numbers
Total Accepted: 19548 Total Submissions: 130867My Submissions
Question Solution
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
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Hide Tags
Have you met this question in a real interview?
Yes
No
这道题开始理解题目搞错了,以为是比较一个带有小数点的两个数的大小就写了下面的代码:
#include<iostream> #include<string> #include<queue> using namespace std; int compareVersion(string version1, string version2) { queue<char> que1,que2; int xiaosudian1=0; int xiaoshudian2=0; //将version1的小数点前面的数进队列 for(int i=0;i<version1.size();i++) { if(version1[i]!=‘.‘) que1.push(version1[i]); else { xiaosudian1=i; break; } } //将version2的小数点前面的数进队列 for(int i=0;i<version2.size();i++) { if(version2[i]!=‘.‘) que2.push(version2[i]); else { xiaoshudian2=i; break; } } //将前面的那些0给去掉 if(que1.size()!=0) { while(1) { if(que1.size()!=0&&que1.front()==‘0‘) que1.pop(); else break; } } //将前面的那些0给去掉 if(que2.size()!=0) { while(1) { if(que2.size()!=0&&que2.front()==‘0‘) que2.pop(); else break; } } if(que1.size()>que2.size()) return 1; else if(que1.size()<que2.size()) return -1; else { if(xiaosudian1!=0) for(int j=xiaosudian1+1;j<version1.size();j++) que1.push(version1[j]); if(xiaoshudian2!=0) for(int j=xiaoshudian2+1;j<version2.size();j++) que2.push(version2[j]); } int k=0; while((!que1.empty())&&(!que2.empty())) { if(que1.front()>que2.front()) return 1; else if(que1.front()<que2.front()) return -1; que1.pop(); que2.pop(); } //将小数点后面的最后那些没有用的0去掉 if((!que1.empty())&&(que2.empty())) { while(!que1.empty()) { if(que1.front()!=‘0‘) return 1; else que1.pop(); } return 0; } //将小数点后面的最后那些没有用的0去掉 if((que1.empty())&&(!que2.empty())) { while(!que2.empty()) { if(que2.front()!=‘0‘) return -1; else que2.pop(); } return 0; } return 0; } int main() { string str1="01.00"; string str2="01.01"; cout<<compareVersion(str1,str2)<<endl; system("pause"); return 1; }
其实这道题主要的意思是说,两个string中只含有数字和小数点,而小数点也不止一个,它们的作用只是为了把数字分开而分开后依次进行比较:
其实意思很简单,每一个字符串中有一些数字和‘.’,‘.’的作用只是为了把数字分开,然后依次比较大小
在自己写的很土的方法中,就是简单的先把两个string分解到对应的vector当中,这里有几个需要注意的地方
两个字符串中的数字长度不是相等的,所以如果前面都相等还要看后面
11.22.33.00.00000 = 11.22.33
11.22.33.01 > 11.22.33
还有就是字符串最后面是没有‘.‘符号的,这里需要注意