Skip to content

Instantly share code, notes, and snippets.

@rajubd49
Last active August 5, 2019 10:47
Show Gist options
  • Save rajubd49/8d3d0f2355cae443cd4be73314f3da7b to your computer and use it in GitHub Desktop.
Save rajubd49/8d3d0f2355cae443cd4be73314f3da7b to your computer and use it in GitHub Desktop.
Swift implementation of Hash Map
import UIKit
var string = "1337"
func convert(string: String) -> Int? {
var total = 0
let valueMap = [
"0" as Character : 0,
"1" : 1,
"2" : 2,
"3" : 3,
"4" : 4,
"5" : 5,
"6" : 6,
"7" : 7,
"8" : 8,
"9" : 9,
]
//Two ways to solve this problem
//1337 = 1000 + 300 + 30 + 7
//1337 = 1*10^3 + 3*10^2 + 3*10^1 + 7*10^0
for (index, character) in string.enumerated() {
let exponent = string.count - index - 1
if let vaule = valueMap[character] {
let number = Decimal(vaule) * pow(10, exponent)
total += NSDecimalNumber(decimal: number).intValue
} else {
return nil
}
}
return total
}
convert(string: string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment