Compare Version Numbers

来源:互联网 发布:域名需要实名认证 编辑:程序博客网 时间:2024/06/06 01:55

Compare Version Numbers:

虽然之前接触过用stream做string与int转换的方法,但是看到这道题还是想着用for循环去手动实现。分享一份网上的特别简洁的代码,也是让我体会到了代码的美感。

class Solution {public:    int compareVersion(string version1, string version2) {        for(auto& ch: version1) { if (ch == '.') ch = ' '; }        for(auto& ch: version2) { if (ch == '.') ch = ' '; }        stringstream ss1(version1), ss2(version2);        int not_consumed[2] = {1, 1};        int v1;        int v2;        while(not_consumed[0] || not_consumed[1]) {            if (!(ss1 >> v1)) {                not_consumed[0] = 0;                v1 = 0;            }            if (!(ss2 >> v2)) {                not_consumed[1] = 0;                v2 = 0;            }            if (v1 > v2) {                return 1;            } else if (v1 < v2) {                return -1;            }        }        return 0;    }};


0 0
原创粉丝点击