本文主要是介绍LeetCode //C - 165. Compare Version Numbers,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
165. Compare Version Numbers
Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots ‘.’. The value of the revision is its integer conversion ignoring leading zeros.
To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0.
Return the following:
- If version1 < version2, return -1.
- If version1 > version2, return 1.
- Otherwise, return 0.
Example 1:
Input: version1 = “1.2”, version2 = “1.10”
Output: -1
Explanation:
version1’s second revision is “2” and version2’s second revision is “10”: 2 < 10, so version1 < version2.
Example 2:
Input: version1 = “1.01”, version2 = “1.001”
Output: 0
Explanation:
Ignoring leading zeroes, both “01” and “001” represent the same integer “1”
Example 3:
Input: version1 = “1.0”, version2 = “1.0.0.0”
Output: 0
Explanation:
version1 has less revisions, which means every missing revision are treated as “0”.
Constraints:
- 1 <= version1.length, version2.length <= 500
- version1 and version2 only contain digits and ‘.’.
- version1 and version2 are valid version numbers.
- All the given revisions in version1 and version2 can be stored in a 32-bit integer.
From: LeetCode
Link: 165. Compare Version Numbers
Solution:
Ideas:
- Reading Revisions: The revised function reads each revision number directly from the string without splitting it into tokens. This avoids potential issues with strtok.
- Resetting Values: After comparing each revision, the values are reset for the next iteration.
- Edge Case Handling: By reading and comparing revisions directly, the function correctly handles cases where versions have different lengths or leading zeros.
Code:
int compareVersion(char* version1, char* version2) {int num1 = 0, num2 = 0;char* p1 = version1;char* p2 = version2;while (*p1 != '\0' || *p2 != '\0') {// Read the next revision number from version1while (*p1 != '\0' && *p1 != '.') {num1 = num1 * 10 + (*p1 - '0');p1++;}// Read the next revision number from version2while (*p2 != '\0' && *p2 != '.') {num2 = num2 * 10 + (*p2 - '0');p2++;}// Compare the revision numbersif (num1 < num2) {return -1;} else if (num1 > num2) {return 1;}// Reset the numbers and move to the next revisionnum1 = 0;num2 = 0;if (*p1 == '.') p1++;if (*p2 == '.') p2++;}return 0;
}
这篇关于LeetCode //C - 165. Compare Version Numbers的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!