LeetCode 之 Compare Version Numbers — C 实现
2015-06-11 20:41
323 查看
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.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
比较两个版本号 version1 和 version2.
如果 version1 > version2 返回 1,如果 version1 < version2 返回 -1,否则返回 0.
假设版本号字符串非空且只包含数字和 '.' 字符。
字符 '.' 不代表小数点,只是版本数字的分隔符。
例如,2.5 代表主版本号二,次版本号 5.
下面是一个版本大小的实例:
0.1 < 1.1 < 1.2 < 13.37
分析:
先提取 version1 和 version2 每部分的版本号并转化成整数,然后比较对应部分的版本号,如果都相等,再比较没有比较完的剩下的版本号,如果都为 0,则两版本相等,不为 0,则该版本大。
注意剩下没有参与比较的次版本号为 0的情况。
int compareVersion(char* version1, char* version2) { int numv1 = 0, numv2 = 0; char *pv1 = version1, *pv2 = version2; if(!pv1 || !pv2)/*空指针*/ { return 0; } while(*pv1 && *pv2) { numv1 = numv2 = 0; while(*pv1 && *pv1 != '.') { numv1 = 10*numv1 + (*pv1 - '0'); ++pv1; } while(*pv2 && *pv2 != '.') { numv2 = 10*numv2 + (*pv2 - '0'); ++pv2; } if(numv1 > numv2) /* v1 > v2 */ { return 1; } else if(numv1 < numv2) /* v1 < v2 */ { return -1; } /*相等,比较次版本号*/ if(*pv1) ++pv1; if(*pv2) ++pv2; } if(*pv1 && !*pv2) /*v1有更小的版本号*/ { numv1 = 0; while(*pv1) { while(*pv1 && *pv1 != '.') { numv1 = 10*numv1 + (*pv1 - '0'); ++pv1; } if(numv1 != 0) /*次版本号不为0,v1>v2 */ return 1; if(*pv1) /*此版本号为0,继续比较*/ ++pv1; } return 0; /*次版本号全为0 */ } else if(!*pv1 && *pv2) /*v2有更小的版本号*/ { numv2 = 0; while(*pv2) { while(*pv2 && *pv2 != '.') { numv2 = 10*numv2 + (*pv2 - '0'); ++pv2; } if(numv2 != 0) /*次版本号不为0,v1<v2 */ return -1; if(*pv2) /*此版本号为0,继续比较*/ ++pv2; } return 0;/*次版本号全为0*/ } return 0; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)