题解 | 比较版本号
比较版本号
https://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 比较版本号 * @param version1 string字符串 * @param version2 string字符串 * @return int整型 */ #include <stdio.h> #include <stdlib.h> #include <string.h> int compare(char* version1, char* version2 ) { // write code here char* strs1 = strtok(version1, "."); int num1[32] = {0}; int num2[32] = {0}; int lenth1 = 0; int lenth2 = 0; int lenth = 0; while(strs1 != NULL) { num1[lenth1++] = atoi(strs1); strs1 = strtok(NULL, "."); } char* strs2 = strtok(version2, "."); while(strs2 != NULL) { num2[lenth2++] = atoi(strs2); strs2 = strtok(NULL, "."); } lenth = lenth1 > lenth2 ? lenth1 : lenth2; for (int i = 0; i < lenth; i++) { if(num1[i] > num2[i]) { return 1; } if (num1[i] < num2[i]){ return -1; } } return 0; }