Skip to content

Commit

Permalink
[Math] Add a solution to Integer to English Words, and update Add Bin…
Browse files Browse the repository at this point in the history
…ary to Swift 3.0
  • Loading branch information
Yi Gu committed Dec 31, 2016
1 parent 5c22dc5 commit 671fb30
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 18 deletions.
28 changes: 10 additions & 18 deletions Math/AddBinary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,24 @@
*/

class AddBinary {
func addBinary(a: String, _ b: String) -> String {
var res = ""
var aChars = [Character](a.characters)
var bChars = [Character](b.characters)

var i = aChars.count - 1
var j = bChars.count - 1
var carry = 0
var num = 0
func addBinary(_ a: String, _ b: String) -> String {
var sum = 0, carry = 0, res = ""
let aChars = Array(a.characters), bChars = Array(b.characters)
var i = aChars.count - 1, j = bChars.count - 1

while i >= 0 || j >= 0 || carry > 0 {
num = carry

sum = carry
if i >= 0 {
num += Int(String(aChars[i]))!
sum += Int(String(aChars[i]))!
i -= 1
}
if j >= 0 {
num += Int(String(bChars[j]))!
sum += Int(String(bChars[j]))!
j -= 1
}

carry = num / 2
num = num % 2

res = String(num) + res
carry = sum / 2
sum = sum % 2
res = String(sum) + res
}

return res
Expand Down
48 changes: 48 additions & 0 deletions Math/IntegerEnglishWords.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Question Link: https://leetcode.com/problems/integer-to-english-words/
* Primary idea: Divide and mod 1000, 100, and 10 to get string for each digit
* Time Complexity: O(n), Space Complexity: O(1)
*
*/

class IntegerEnglishWords {
func numberToWords(_ num: Int) -> String {
let l1 = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
let l2 = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
let l3 = "Hundred"
let l4 = ["Thousand", "Million", "Billion"]
var res = "", num = num, digit = -1

if num == 0 {
return "Zero"
}

while num > 0 {
var temp = "", token = num % 1000

if token > 99 {
temp += "\(l1[token / 100]) \(l3) "
token %= 100
}

if token > 19 {
temp += "\(l2[token / 10 - 2]) "
token %= 10
}

if token > 0 {
temp += "\(l1[token]) "
}

if digit != -1 && temp != "" {
res = temp + l4[digit] + " " + res
} else {
res = temp + res
}
digit += 1
num /= 1000
}

return String(res.characters.dropLast())
}
}

0 comments on commit 671fb30

Please sign in to comment.