每日一題
日期
2025/9/19
步驟
- 把字串分割後轉換成整數 (Int)
- 走訪兩個整數陣列,如果有一個先走訪完了就補零
- 兩個值不一樣的時候根據題目要求回傳 1 或 -1
程式碼
class Solution {
func compareVersion(_ version1: String, _ version2: String) -> Int {
let v1 = integers(version1)
let v2 = integers(version2)
let n = max(v1.count, v2.count)
for index in 0..<n {
let one = value(of: v1, at: index)
let two = value(of: v2, at: index)
if one != two {
return one > two ? 1 : -1
}
}
return 0
}
private func integers(_ string: String) -> [Int] {
string.split(separator: ".").compactMap { Int($0) }
}
private func value(of numbers: [Int], at index: Int) -> Int {
index < numbers.count ? numbers[index] : 0
}
}
















