-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.swift
More file actions
29 lines (24 loc) · 815 Bytes
/
Solution.swift
File metadata and controls
29 lines (24 loc) · 815 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
Recursive Multiply
Write a recursive function to multiply two positive integers without using the * operator. You can use addition, substraction and bit shifting, but you should minimize the number of those operations.
*/
func multiply(_ first: Int, _ second: Int) -> Int {
let bigger = first > second ? first : second
let smaller = first > second ? second : first
return multiplyHelper(smaller, bigger)
}
func multiplyHelper(_ smaller: Int, _ larger: Int) -> Int {
if smaller == 0 {
return 0
} else if smaller == 1 {
return larger
}
let s = smaller >> 1
let halfProd = multiplyHelper(s, larger)
if smaller % 2 == 0 {
return halfProd + halfProd
} else {
return halfProd + halfProd + larger
}
}
print(multiply(77, 10))