Skip to content

Instantly share code, notes, and snippets.

@BeauNouvelle
Last active April 22, 2019 13:25
Show Gist options
  • Save BeauNouvelle/2df0629ada7587bdf9019b96878f72ea to your computer and use it in GitHub Desktop.
Save BeauNouvelle/2df0629ada7587bdf9019b96878f72ea to your computer and use it in GitHub Desktop.
BigInt completed
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) }
@BeauNouvelle
Copy link
Author

Ah not bad! Made the change. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment