/*
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.5 is 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
*/
/*
切割字符串,如果长度为1,补足为2
Error:可能会出现多个版本,因此需要根据两个版本中的居多者补齐,然后
输入一个比较函数,比较每一个子版本
*/
func compareVersion(_ version1: String, _ version2: String) -> Int {
var v1Array = version1.components(separatedBy: ".")
var v2Array = version2.components(separatedBy: ".")
let versionLength = max(v1Array.count, v2Array.count)
for _ in 0..<versionLength-v1Array.count {
v1Array.append("0")
}
for _ in 0..<versionLength-v2Array.count {
v2Array.append("0")
}
//如果相等,则继续比较,如果不等,则直接返回结果
func compareResult(_ v1: String, _ v2: String) -> Int {
if Int(v1)! > Int(v2)! {
return 1
}
else if Int(v1)! < Int(v2)! {
return -1
}
else {
return 0
}
}
var result = 0
for i in 0..<versionLength {
let ret = compareResult(v1Array[i], v2Array[i])
if ret != 0 {
result = ret
break
}
}
return result
}
compareVersion("1.0.1", "1")
165. Compare Version Numbers
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Compare two version numbers version1 and version2. If ver...
- 原题链接:Compare Version Numbers这道题非常有意思,也有一定的难度,下面先给出我的解法: 代...
- 问题 Compare two version numbers version1 and version2.If v...
- Compare two version numbers version1 and version2.If vers...
- Compare two version numbers version1 and version2.If vers...