Created
February 24, 2017 13:19
-
-
Save monyschuk/1a867cfaba594b79fb967a3c60f33cb6 to your computer and use it in GitHub Desktop.
String of decimal digits used to represent an arbitrarily large counter
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
struct DecimalString { | |
var value: String | |
private init(_ value: String) { | |
self.value = value | |
} | |
init(digits string: String) { | |
let digits = CharacterSet.decimalDigits | |
self.value = string.unicodeScalars.filter { digits.contains($0) } .map { String($0) } .joined() | |
} | |
func next() -> DecimalString { | |
var carry = UInt32(1) | |
var digits = value.unicodeScalars.map { $0.value - UnicodeScalar("0").value } | |
for idx in digits.indices.reversed() { | |
let nextDigit = digits[idx] + carry | |
digits[idx] = nextDigit % 10 | |
carry = nextDigit / 10 | |
if carry == 0 { break } | |
} | |
if carry != 0 { | |
digits.insert(1, at: 0) | |
} | |
return DecimalString(digits.map { String($0) }.joined()) | |
} | |
} | |
let d = DecimalString(digits: "ABC99") | |
print(d.next()) | |
print(d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment