[LeetCode] Compare Version Numbers

来源:互联网 发布:苹果7翻译软件 编辑:程序博客网 时间:2024/04/27 05:07

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
解题思路:

首先求用‘.’分隔的版本号的加权和,随后比较加权和的大小。

实现代码:

/*****************************************************************************    *  @COPYRIGHT NOTICE    *  @Copyright (c) 2015, 楚兴    *  @All rights reserved    *  @Version  : 1.0    *  @Author   : 楚兴    *  @Date     : 2015/2/6 21:52    *  @Status   : Accepted    *  @Runtime  : 4 ms*****************************************************************************/#include <iostream>#include <vector>#include <algorithm>using namespace std;class Solution {public:int compareVersion(string version1, string version2) {double v1 = strtod(version1);double v2 = strtod(version2);if (v1 == v2){return 0;}return v1 > v2 ? 1 : -1;}double strtod(string str){int i = 0;double sum = 0;double ratio = 1;int num = 0;while (i < str.size()){if (str[i] == '.'){sum += num / ratio; num = 0; ratio *= 10; //权重降级}if (str[i] >= '0' && str[i] <= '9'){num = num * 10 + str[i] - '0';}i++;}sum += num / ratio;return sum;}};int main(){Solution s;cout<<s.compareVersion("1","0")<<endl;cout<<s.compareVersion("0.1","1.1")<<endl;cout<<s.compareVersion("1.1","1.2")<<endl;cout<<s.compareVersion("13.37","9.4")<<endl;cout<<s.compareVersion("1.1","1.15")<<endl;cout<<s.compareVersion("1.1","1.01.0")<<endl;system("pause");}

上述程序虽然能够被LeetCode接受,但实际上还是存在问题。在降权的时候,权重问题不好确定。目前的程序在处理版本号“1.2000”和"2.1"时会给出错误结果。同时如果版本号级数较多,会存在小数部分存储不完的情况。故更改如下:

class Solution {public:int compareVersion(string version1, string version2) {int i = 0;int j = 0;while (i < version1.size() || j < version2.size()){int num1 = 0;while(i < version1.size()){if (version1[i] == '.'){i++;break;}else{num1 = num1 * 10 + version1[i] - '0';i++;}}int num2 = 0;while(j < version2.size()){if (version2[j] == '.'){j++;break;}else{num2 = num2 * 10 + version2[j] - '0';j++;}}if (num1 != num2){return num1 > num2 ? 1 : -1;}}return 0;}};

Runtime: 3 ms

分别对比每一段的版本号,如果相同则继续比较下一段。不同则返回。


0 0