forked from WenchaoD/LeetCode_Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Math] Add solution to Integer to Roman
- Loading branch information
Yi Gu
committed
Oct 14, 2016
1 parent
bbe4f5f
commit 00fd625
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/integer-to-roman/ | ||
* Primary idea: Add symbols from big to small, minus relative number as well | ||
* Time Complexity: O(n), Space Complexity: O(1) | ||
* | ||
*/ | ||
|
||
class IntegerToRoman { | ||
func intToRoman(_ num: Int) -> String { | ||
guard num > 0 else { | ||
return "" | ||
} | ||
|
||
let nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] | ||
let symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] | ||
var res = "" | ||
var digit = 0 | ||
var number = num | ||
|
||
while number > 0 { | ||
let current = number / nums[digit] | ||
|
||
for _ in 0 ..< current { | ||
res += symbols[digit] | ||
} | ||
|
||
number -= current * nums[digit] | ||
digit += 1 | ||
} | ||
|
||
return res | ||
} | ||
} |