Last active
August 5, 2019 10:47
-
-
Save rajubd49/8d3d0f2355cae443cd4be73314f3da7b to your computer and use it in GitHub Desktop.
Swift implementation of Hash Map
This file contains hidden or 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
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