Last active
April 22, 2019 13:25
-
-
Save BeauNouvelle/2df0629ada7587bdf9019b96878f72ea to your computer and use it in GitHub Desktop.
BigInt completed
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 | |
import Foundation | |
struct BigInt { | |
var value: String | |
func multiply(right: BigInt) -> BigInt { | |
var leftCharacterArray = value.characters.reversed().map { Int(String($0))! } | |
var rightCharacterArray = right.value.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()) | |
while result.count > 0 && result.first == 0 { | |
result.removeFirst(1) | |
} | |
return BigInt(value: result.map { String($0) }.joined(separator: "")) | |
} | |
} | |
func * (left: BigInt, right: BigInt) -> BigInt { return left.multiply(right: right) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ah not bad! Made the change. Thank you.