Open3

AtCoder入門のサンプルコード:Swift解答版

とんとんぼとんとんぼ

3.2:整数型変数

例題:01

// A - Multiplication 1
// https://atcoder.jp/contests/abc169/tasks/abc169_a
// 実行制限時間: 2.0 sec
// AtCoder入門:例題01
import Foundation

private func readInt2() -> (Int, Int) {
    let value = readLine()!.split(separator: " ").map{ Int(String($0))!}
    return (value[0], value[1])
}

let (A, B) = readInt2()

private func process() -> Int {
    return A * B
}

print(process())

例題:02

// A - Product
// https://atcoder.jp/contests/abc086/tasks/abc086_a
// 実行制限時間: 2.0 sec
// AtCoder入門:例題02
import Foundation

private func readInt2() -> (Int, Int) {
    let value = readLine()!.split(separator: " ").map{ Int(String($0))!}
    return (value[0], value[1])
}

let (a, b) = readInt2()

private func process() -> String {
    let product = a * b
    if product % 2 == 0 {
        return "Even"
    } else {
        return "Odd"
    }
}

print(process())

こっちの方が読みやすいかも?

private func process() -> String {
    let product = a * b
    if product % 2 == 0 {
        return "Even"
    }
    return "Odd"
}

例題:03

// A - Serval vs Monster
// https://atcoder.jp/contests/abc153/tasks/abc153_a
// 実行制限時間: 2.0 sec
// AtCoder:例題03
import Foundation

private func readInt2() -> (Int, Int) {
    let value = readLine()!.split(separator: " ").map{ Int(String($0))!}
    return (value[0], value[1])
}

let (H, A) = readInt2()

private func process() -> Int {
    // HがAで割り切れる場合
    if H % A == 0 {
        return H / A
    }
    // HがAで割り切れない場合
    let times = H / A
    return times + 1
}

print(process())
とんとんぼとんとんぼ

3-3:while文とfor文

例題:04

import Foundation

private func readInt() -> Int {
    Int(readLine()!)!
}

private func readInt2() -> (Int, Int) {
    let value = readLine()!.split(separator: " ").map{ Int(String($0))!}
    return (value[0], value[1])
}

let K = readInt()
let (A, B) = readInt2()


private func process() -> Bool {
    var flag: Bool = false
    
    for i in A ... B {
        if i % K == 0 {
            flag = true
        }
    }
    return flag
}

print(process() ? "OK":"NG")

別解

別解やで~

private func process() -> Bool {
    var flag = false
    
    let a = B / K // 1以上、B以下のKの倍数の個数
    let l = (A - 1) / K // 1以上、A-1以下のKの倍数の個数
    
    // A以上B以下のKの倍数の個数から判定
    if a - l >= 1 {
        flag = true
    }
    return flag
}

例題05

再代入をしないでやる方法があったら、教えてクレメンス

import Foundation

private func readInt3() -> (Int, Int, Int) {
    let value = readLine()!.split(separator: " ").map{ Int(String($0))! }
    return (value[0], value[1], value[2])
}

let (N, A, B) = readInt3()

private func process() -> Int {
    var result = 0
    
    for i in 0...N {
        let x = calcSumDigits(i)
        
        if A <= x && x <= B {
            result += i
        }
    }
    
    return result
}

private func calcSumDigits(_ N: Int) -> Int {
    var n = N // Swiftの引数は定数になるので、再代入
    var sum_digit = 0 // 各桁の和
    while (n > 0) {
        sum_digit += n % 10
        n /= 10
    }
    
    return sum_digit
}

print(process())