Roman Numeral Converter In Swift
I did this, which works for 1 to 4999
let initial = 1980
var val = initial
var countForRoman : [(rom: String, num: Int)] = [] // how many occurences of romanNumbers; don't use dictionaries as not ordered
for (index, number) in numberValue.enumerated() {
let x = val / number
if x > 0 {
countForRoman.append((romanNumeral[index], x))
val = val - x * number
}
}
print(countForRoman) // Just to see how it converted
var romanString = ""
for pairs in countForRoman {
let iter = pairs.num
for _ in 1 ... iter { romanString += pairs.rom }
}
print(initial, "in roman is", romanString)
Example with 1980:
[(rom: "M", num: 1), (rom: "CM", num: 1), (rom: "L", num: 1), (rom: "X", num: 3)]
1980 in roman is MCMLXXX
If you want to go beyond 4999 (here up to 399 999):
var numberValue = [100_000, 90_000, 50_000, 40_000, 10_000, 9000, 5000, 4000, 1000,900,500,400,100,90,50,40,10,9,5,4,1]
var romanNumeral = [
"(C)",
"(X)(C)",
"(L)",
"(X)(L)",
"(X)",
"M(X)",
"(V)",
"M(V)",
"M",
"CM",
"D",
"CD",
"C",
"XC",
"L",
"XL",
"X",
"IX",
"V",
"IV",
"I"
]
let initial = 9999
var val = initial
var countForRoman : [(rom: String, num: Int)] = [] // how many occurences of romanNumbers; don't use dictionaries as not ordered
for (index, number) in numberValue.enumerated() {
let x = val / number
if x > 0 {
countForRoman.append((romanNumeral[index], x))
val = val - x * number
}
}
print(countForRoman) // Just to see how it converted
var romanString = ""
for pairs in countForRoman {
let iter = pairs.num
for _ in 1 ... iter { romanString += pairs.rom }
}
print(initial, "in roman is", romanString)
To get
[(rom: "M(X)", num: 1), (rom: "CM", num: 1), (rom: "XC", num: 1), (rom: "IX", num: 1)]
9999 in roman is M(X)CMXCIX
For 39999
[(rom: "(X)", num: 3), (rom: "M(X)", num: 1), (rom: "CM", num: 1), (rom: "XC", num: 1), (rom: "IX", num: 1)]
39999 in roman is (X)(X)(X)M(X)CMXCIX
For 129_999
[(rom: "(C)", num: 1), (rom: "(X)", num: 2), (rom: "M(X)", num: 1), (rom: "CM", num: 1), (rom: "XC", num: 1), (rom: "IX", num: 1)]
129999 in roman is (C)(X)(X)M(X)CMXCIX
Just encapsulate this code in the convert Function and you get it.
How to convert a roman numeral to an NSNumer
Here are a couple of resources that may help you:
Roman Numbers Convert
-This one is probably the better of the two as this has forward/backward translation
pzearfoss / NSNumber-RomanNumerals
-This is a simple category; however, it only converts NSNumber to Roman Numeral. You may be able to tweak it to go the other way around.
Basic program to convert integer to Roman numerals?
One of the best ways to deal with this is using the divmod
function. You check if the given number matches any Roman numeral from the highest to the lowest. At every match, you should return the respective character.
Some numbers will have remainders when you use the modulo function, so you also apply the same logic to the remainder. Obviously, I'm hinting at recursion.
See my answer below. I use an OrderedDict
to make sure that I can iterate "downwards" the list, then I use a recursion of divmod
to generate matches. Finally, I join
all generated answers to produce a string.
from collections import OrderedDict
def write_roman(num):
roman = OrderedDict()
roman[1000] = "M"
roman[900] = "CM"
roman[500] = "D"
roman[400] = "CD"
roman[100] = "C"
roman[90] = "XC"
roman[50] = "L"
roman[40] = "XL"
roman[10] = "X"
roman[9] = "IX"
roman[5] = "V"
roman[4] = "IV"
roman[1] = "I"
def roman_num(num):
for r in roman.keys():
x, y = divmod(num, r)
yield roman[r] * x
num -= (r * x)
if num <= 0:
break
return "".join([a for a in roman_num(num)])
Taking it for a spin:
num = 35
print write_roman(num)
# XXXV
num = 994
print write_roman(num)
# CMXCIV
num = 1995
print write_roman(num)
# MCMXCV
num = 2015
print write_roman(num)
# MMXV
Convert Int to String in Swift
Converting Int
to String
:
let x : Int = 42
var myString = String(x)
And the other way around - converting String
to Int
:
let myString : String = "42"
let x: Int? = myString.toInt()
if (x != nil) {
// Successfully converted String to Int
}
Or if you're using Swift 2 or 3:
let x: Int? = Int(myString)
Converting Roman Numerals To Decimal
It will be good if you traverse in reverse.
public class RomanToDecimal {
public static void romanToDecimal(java.lang.String romanNumber) {
int decimal = 0;
int lastNumber = 0;
String romanNumeral = romanNumber.toUpperCase();
/* operation to be performed on upper cases even if user
enters roman values in lower case chars */
for (int x = romanNumeral.length() - 1; x >= 0 ; x--) {
char convertToDecimal = romanNumeral.charAt(x);
switch (convertToDecimal) {
case 'M':
decimal = processDecimal(1000, lastNumber, decimal);
lastNumber = 1000;
break;
case 'D':
decimal = processDecimal(500, lastNumber, decimal);
lastNumber = 500;
break;
case 'C':
decimal = processDecimal(100, lastNumber, decimal);
lastNumber = 100;
break;
case 'L':
decimal = processDecimal(50, lastNumber, decimal);
lastNumber = 50;
break;
case 'X':
decimal = processDecimal(10, lastNumber, decimal);
lastNumber = 10;
break;
case 'V':
decimal = processDecimal(5, lastNumber, decimal);
lastNumber = 5;
break;
case 'I':
decimal = processDecimal(1, lastNumber, decimal);
lastNumber = 1;
break;
}
}
System.out.println(decimal);
}
public static int processDecimal(int decimal, int lastNumber, int lastDecimal) {
if (lastNumber > decimal) {
return lastDecimal - decimal;
} else {
return lastDecimal + decimal;
}
}
public static void main(java.lang.String args[]) {
romanToDecimal("XIV");
}
}
How to convert Decimal to String with two digits after separator?
This should work
extension Decimal {
var formattedAmount: String? {
let formatter = NumberFormatter()
formatter.generatesDecimalNumbers = true
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
return formatter.string(from: self as NSDecimalNumber)
}
}
Related Topics
How to Integrate Mapbox Sdk with Swiftui
Swift Generic Protocol Function Parameters
Should I Remove All Skspritenodes and Labels When I Switch from One Node to Another
Contacts Not Recognized When Body Is Changed from Circle to Rectangle
Access Enum Associated Value as Optional
Display Data in Two Different Tableview in the Same View in Swift
Enum Method Returning a Dynamic Type
Swift Updating Screen in Between Steps of While Loop
Check If the Username Exist in Firebase
Swift: How to Get Information for an Application Which Is Not Running
Xctest Unit Test Data Response Not Set in Test After Viewdidload
Autoscrolling Infinite Effect in .Linear Type of Icarousel in Swift
How to Read Ansi Escape Code Response Value in Swift
Cannot Read Property 'Keycode' 'Character' Assertion Failure When Detect Modifier Key + Numeric Key
A Method Without Parameters Is Calling for an Argument