Created
May 22, 2020 10:41
-
-
Save xsleonard/e4481506896763cb59a84d63a789888f to your computer and use it in GitHub Desktop.
Distance between Int64 in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Int64 { | |
/* | |
Returns the absolute distance between two Int64 values as a UInt64. | |
A UInt64 is required to represent the range of possible distance values. | |
*/ | |
func distanceTo(_ other: Int64) -> UInt64 { | |
if self == other { | |
return 0 | |
} | |
if self > other { | |
return other.distanceTo(self) | |
} | |
let (distance, overflow) = other.subtractingReportingOverflow(self) | |
if !overflow { | |
return UInt64(distance) | |
} | |
// Int64.max minus any negative Int64 is too large to fit into an Int64. Convert it to a Uint64. | |
// Take the difference between 0 and the negative number and add it to positive number, as UInt64 | |
let lowerDistance = self == Int64.min ? UInt64(Int64.max) + 1 : UInt64(-self) | |
return lowerDistance + UInt64(other) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment