gpt4 book ai didi

ios - 获取字符串中字符的频率计数时过滤器的使用不明确

转载 作者:可可西里 更新时间:2023-11-01 01:57:50 26 4
gpt4 key购买 nike

我实现了一个使用 Swift 计算汉明距离的函数,它使用异或运算 x ^ y 来获取不同的位。然后,我将结果从 Int 转换为 8 个字符的 String,这是我的 Xor 的 8 位表示。但是,我收到错误:

编译错误:“过滤器”的使用不明确

class Solution {
func hammingDistance(_ x: Int, _ y: Int) -> Int {
let xor = x ^ y //xor: compares bits
let xorBinary = String(xor, radix: 2)
let xor8BitBinaryStr = String(repeating: Character("0"), count: 8 - xorBinary.count) + xorBinary

return xor8BitBinaryStr.filter({ $0 == "1" }).count
}
}

let c = Solution()
print(c.hammingDistance(1, 4)) //prints 2

最佳答案

你可以这样过滤以避免编译器混淆,

let items = xor8BitBinaryStr.filter({ $0 == "1"})
return items.count

return Array(xor8BitBinaryStr).filter({ $0 == "1" }).count

关于ios - 获取字符串中字符的频率计数时过滤器的使用不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49892672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com