【问题标题】:Swift string iterate and compareSwift 字符串迭代和比较
【发布时间】:2016-06-22 20:08:56
【问题描述】:

我在 CodinGame 网站上玩游戏。任务是找到最接近零的数字。这是给你的。

let n = Int(readLine()!)! // the number of temperatures to analyse
let temps = readLine()! // the n temperatures expressed as integers ranging from -273 to 5526

我不知道该怎么做。我猜有很多方法可以解决。

【问题讨论】:

    标签: swift string


    【解决方案1】:

    所以你有一个 String 包含类似 "4 -6 8 12 -12" 的东西,你想提取最接近零的 Int

    解决办法

    import Foundation
    
    let text = "4 -6 8 12 -12"
    let numbers = text.componentsSeparatedByString(" ").flatMap { Int($0) }
    if let closestToZero = numbers.minElement({ abs($0) < abs($1)}) {
        print(closestToZero) // -1
    }
    

    精简版

    相同的逻辑,更少的代码

    let closestToZero = text.componentsSeparatedByString(" ")
        .flatMap { Int($0) }
        .minElement{ abs($0) < abs($1) }
    

    【讨论】:

    • 抱歉这个含糊的问题。 temps 是一个字符串。 “4 -6 8 12 -12”
    • @BobbyB:没问题,我更新了我的代码,请看一下。
    • 感谢您的更新。我认为这就是我需要的,但它似乎不起作用。收到此错误 Answer.swift:19:15: error: value of type 'String' has no member 'componentsSeparatedByString' 我认为该网站无法像应有的那样快速处理。
    • @BobbyB:因为你需要import Foundation
    • 是的,就是这样。谢谢你。我认为我遇到了问题,因为不是import Foundation 现在我需要弄清楚关闭。旅程会很长。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多