华为OD机试真题2023_Swift_100_对称字符串

g
// 对称字符串
    func HW2023007() {
        // 测试用例
        var lineArr: [String] = []
//        lineArr = ["64 73709551616"]
//        lineArr = ["1 0", "2 1", "3 1", "4 3", "5 8"]
        // 开始代码
        let _ = readLine()
        while let line = readLine() {
            lineArr.append(String(line))
        }
        for i in lineArr {
            let arr = String(i).components(separatedBy: " ").map { Int($0) ?? 0}
            let maxNum: Double = pow(Double(2), Double(arr.first! - 1))
            let res = creatSymmetryString(maxNum, Double(arr.last!), 0)
            print((res % 2 == 0 ? "red" : "blue") + "\(res)")
        }
    }
//  n: 总字符总个数 k:字符索引 reverse:翻转次数 reture:翻转次数
    func creatSymmetryString(_ n: Double, _ k: Double, _ reverse: Int) -> Int {
        var reverse = reverse
        if n == 1 {
            return reverse
        }
        let half: Double = n / 2
        if k < half {
            reverse += 1
            return creatSymmetryString(half, k, reverse)
        }else {
            return creatSymmetryString(half, k-half, reverse)
        }
    }

你可能感兴趣的:(华为OD机试真题2023_Swift_100_对称字符串)