【leetcode】Compare Version Numbers

来源:互联网 发布:域名注册可靠吗 编辑:程序博客网 时间:2024/06/16 15:23

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

分析:

字符串中涉及多个小数点,需要依次找出,分割出小数点前的部分。越往前,权值越大,将子串转换为数字,然后累加。比较两个数的大小即可。

class Solution {public:    int compareVersion(string version1, string version2) {    double v1=0,v2=0;int pos1=0,count1=0;while (pos1>=0){pos1=version1.find('.');v1+=atoi(version1.substr(0,pos1).c_str())*(double)pow((double)10,-count1);count1++;version1=version1.substr(pos1+1,version1.length());}int pos2=0,count2=0;while (pos2>=0){pos2=version2.find('.');v2+=atoi(version2.substr(0,pos2).c_str())*(double)pow((double)10,-count2);count2++;version2=version2.substr(pos2+1,version2.length());}if (v1>v2)return 1;else if(v1<v2)return -1;elsereturn 0;    }};

需要注意的问题:

1、字符串基本操作。如find(),substr(pos1,pos2),atoi(char *), c_str()

2、一开始用的变量为float型,但是当测试数据为"0.9.9.9.9.9.9.9.9.9.9.9.9", "1.0"时,float的位数不够(6~7),导致结果不准确。换成double后解决(15~16)

0 0