[LeetCode165] Compare Version Numbers


题目:

Compare two version numbersversion1andversion2.
Ifversion1>version2return 1, ifversion1<version2return -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.5is 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

分类:String

代码:

 1 class Solution {
 2 public:
 3     int compareVersion(string version1, string version2) {
 4         /*
 5         vector<int> v1;
 6         vector<int> v2;
 7         istringstream ss1(version1);
 8         istringstream ss2(version2);
 9         while(!ss1.eof())
10         {
11             string word;
12             getline(ss1,word,'.');
13             int num;
14             stringstream ss;
15             ss << word;
16             ss >> num;
17             v1.push_back(num);
18         }
19         while(!ss2.eof())
20         {
21             string word;
22             getline(ss2,word,'.');
23             int num;
24             stringstream ss;
25             ss << word;
26             ss >> num;
27             v2.push_back(num);
28         }
29         
30         for(int i = 0; i < max(v1.size(),v2.size()); ++i)
31         {
32             int num1,num2;
33             if(i < v1.size())
34                 num1 = v1[i];
35             else
36                 num1 = 0;
37             if(i < v2.size())
38                 num2 = v2[i];
39             else
40                 num2 = 0;
41             if(num1 > num2)
42                 return 1;
43             else if(num1 < num2)
44                 return -1;
45         }
46         return 0;
47         */
48         
49         stringstream ss1(version1),ss2(version2);
50         int num1 = 0, num2 = 0;
51         char op;//符号. 每次读入一个int 跳过.
52         
53         while(!ss1.fail() || !ss2.fail())
54         {
55             ss1 >> num1;
56             ss2 >> num2;
57             if(ss1.fail())
58                 num1 = 0;
59             if(ss2.fail())
60                 num2 = 0;
61             if(num1 < num2)
62                 return -1;
63             else if(num1 > num2)
64                 return 1;
65             ss1 >> op;
66             ss2 >> op;
67         }
68         
69         return 0;
70     }
71     
72 };

优质内容筛选与推荐>>
1、基于SignalR的小型IM系统
2、【回文自动机】 HDU 5421 Victor and String
3、互联网史上10大经典商战
4、asp.net解决高并发的方案.
5、几何画板课件:圆周角与圆心角关系


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号