Last active
June 26, 2019 04:05
-
-
Save yanil3500/1117367d45e1509af32d1c38d3540656 to your computer and use it in GitHub Desktop.
[String To Integer]
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
import Foundation | |
precedencegroup ExponentiationPrecedence { | |
associativity: right | |
higherThan: MultiplicationPrecedence | |
} | |
infix operator **: ExponentiationPrecedence | |
func ** (lhs: Int, rhs: Int) -> Int { | |
return Int(pow(Float(lhs), Float(rhs))) | |
} | |
var sampleString = "3459" | |
extension String { | |
func convert() -> Int? { | |
var result: Int = 0 | |
// building value map | |
var valueMap = [ | |
"0" as Character: 0, | |
"1": 1, | |
"2": 2, | |
"3": 3, | |
"4": 4, | |
"5": 5, | |
"6": 6, | |
"7": 7, | |
"8": 8, | |
"9": 9 | |
] | |
// example: 3459 | |
// 3459 = (3 * 10^3) + 4 * 10^2 + 5 * 10^1 + 9 * 10^0 | |
// value * (10 ** exponent) | |
for (i, c) in self.enumerated() { | |
let exponent = self.count - i - 1 | |
if let value = valueMap[c] { | |
result += value * (10 ** exponent) | |
} else { | |
return nil | |
} | |
} | |
return result | |
} | |
} | |
sampleString.convert() // 3459 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment