Menu
CoddyTech

Numbers and Conversion

Lesson 3 of 48 in Coddy's Swift for Ruby Developers course.

Ruby Integer grows to represent large exact results subject to available memory. Division between integers floors the result, and fdiv explicitly requests a floating-point quotient. Ruby modulo follows its own signed-division convention; do not assume negative-input behavior matches Swift just because positive examples agree.

Swift Int has a fixed width, 64 bits on this runtime, and ordinary overflow traps. Integer division truncates toward zero. Convert operands to Double before dividing for a fractional result; converting an already-truncated quotient later cannot restore its fraction.

The source produces -4 for integer division and -3.5 for floating division, while Swift integer division produces -3. The task uses bounded nonnegative inputs, but knowing the rounding rule prevents errors when a helper is reused with negative values.

Complete Ruby comparison program:

puts(-7 / 2)
puts(-7.fdiv(2))
puts(10**30 > 2**63)

Complete Swift comparison program, compiled from these files:

main.swift

print(-7 / 2)
print(Double(-7) / 2)
print(Int.max > 0)
challenge icon

Challenge

Easy

Implement clockParts(_ minutes: Int) -> String. Input is total minutes, 0 through 10000. Return whole hours, a colon, then remaining minutes, without zero padding.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return clockParts(181) == "3:1" && clockParts(60) == "1:0"
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Ruby Developers

Practice on your own: Swift playground