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
分析题目:求版本号大小,题意: 题意很清晰,就是比较“版本号”大小,给定的版本号version1和version2是字符串类型的,当version1>version2的时候,返回1,反之返回-1。
解题思路:字符串从左向右依次遍历,除过字符串的‘.’,其他的字符转换为十进制,两个版本进行比较,这样利用strtol函数就特别方便,
long int strtol ( const char * str, char ** endptr, int base );从str指向的字符开始转化,忽略掉前面的空格,遇到错误无法转换的字符则返回,如果endptr不为空,则将该字符存储在endptr里。对前两个函数,base则表示其进制。若进行一次比较之后,没有分出大小(eg.10.2 和10.3)字符串的地址转为‘.’之后的首字母地址进行下一串有效字符的比较。具体代码如下:#include <iostream> #include <stdio.h> #include <string> using namespace std; int compareVersion(string version1, string version2) ; void main() { string a="10.1.5",b="10.2"; cout<<compareVersion(a, b) ; } int compareVersion(string version1, string version2) { int result = 0; char *p1=new char[version1.size()+1]; char *p2=new char[version2.size()+1]; p1=strcpy(p1,version1.c_str()); p2 =strcpy(p2,version2.c_str()); while (result == 0 && (*p1 != '\0' || *p2 != '\0')) { long v1,v2; if (*p1=='\0') { v1=0; } else { v1=strtol(p1, &p1, 10); } if (*p2=='\0') { v2=0; } else { v2=strtol(p2, &p2, 10); } /* long v1 = *p1 == '\0' ? 0 : strtol(p1, &p1, 10); long v2 = *p2 == '\0' ? 0 : strtol(p2, &p2, 10);*/ if (v1 > v2) result = 1; else if (v2 > v1) result = -1; else { if (*p1 != '\0') p1++; if (*p2 != '\0') p2++; } } return result; }
结果为 -1