leetcode 165. 比较版本号

简介

对于java这种功能比较全相对于c++, 比较好写代码, 但是缺点也比较多, 要记住太多的接口语句.

code

class Solution {
    public int compareVersion(String version1, String version2) {
        String [] nums1 = version1.split("\."); // 字符串分割为数组
        String [] nums2 = version2.split("\.");

        int n1 = nums1.length, n2 = nums2.length;

        // compare versions
        int i1, i2;
        for(int i=0; i < Math.max(n1, n2); ++i){
            i1 = i < n1 ? Integer.parseInt(nums1[i]) : 0; // 将字符串解析为数字
            i2 = i < n2 ? Integer.parseInt(nums2[i]) : 0;
            if(i1 != i2) {
                return i1 > i2 ? 1 : -1; 
            }
        }
        return 0;
    }
}

version1 和 version2 的所有修订号都可以存储在 32 位整数中

class Solution {
public:
    int compareVersion(string version1, string version2) {
        int n1=version1.size(),n2=version2.size(),end=max(n1,n2);
        for(int p1=0,p2=0;p1<end||p2<end;p1++,p2++){
            int v1=0,v2=0;
            while(p1<n1&&version1[p1]!='.')v1=v1*10+version1[p1++]-'0';            
            while(p2<n2&&version2[p2]!='.')v2=v2*10+version2[p2++]-'0';
            if(v1>v2)return 1;
            else if(v1<v2)return -1;
        }
        return 0;
    }
};

作者:moao
链接:https://leetcode-cn.com/problems/compare-version-numbers/solution/100-9897-by-moao-q7oa/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14830473.html