Created
April 4, 2017 12:57
-
-
Save BeauNouvelle/3e9bcb2f6d5e35ecfd558b3dc8db7ee6 to your computer and use it in GitHub Desktop.
Multiplication
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
func multiply(left: String, right: String) -> String { | |
var leftCharacterArray = left.characters.reversed().map { Int(String($0))! } | |
var rightCharacterArray = right.characters.reversed().map { Int(String($0))! } | |
var result = [Int](repeating: 0, count: leftCharacterArray.count+rightCharacterArray.count) | |
for leftIndex in 0..<leftCharacterArray.count { | |
for rightIndex in 0..<rightCharacterArray.count { | |
let resultIndex = leftIndex + rightIndex | |
result[resultIndex] = leftCharacterArray[leftIndex] * rightCharacterArray[rightIndex] + (resultIndex >= result.count ? 0 : result[resultIndex]) | |
if result[resultIndex] > 9 { | |
result[resultIndex + 1] = (result[resultIndex] / 10) + (resultIndex+1 >= result.count ? 0 : result[resultIndex + 1]) | |
result[resultIndex] -= (result[resultIndex] / 10) * 10 | |
} | |
} | |
} | |
result = Array(result.reversed()) | |
return result.map { String($0) }.joined(separator: "") | |
} | |
multiply(left: "2844858348834855723432430", right: "134534523453454540998798789") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment