Skip to content

Instantly share code, notes, and snippets.

@tokyotech
Created March 11, 2015 17:02
Show Gist options
  • Save tokyotech/40807c8aee928bfb65ec to your computer and use it in GitHub Desktop.
Save tokyotech/40807c8aee928bfb65ec to your computer and use it in GitHub Desktop.
Convert positive integer into Roman numerals
#import "NSNumber+conversion.h"
@implementation NSNumber (conversion)
- (NSString*)romanNumerals
{
assert(self.integerValue > 0);
static NSString* characterKey = @"c";
static NSString* valueKey = @"v";
NSArray* romanNumerals = @[
@{
characterKey: @"I",
valueKey: @1
},
@{
characterKey: @"IV",
valueKey: @4
},
@{
characterKey: @"V",
valueKey: @5
},
@{
characterKey: @"IX",
valueKey: @9
},
@{
characterKey: @"X",
valueKey: @10
},
@{
characterKey: @"XL",
valueKey: @40
},
@{
characterKey: @"L",
valueKey: @50
},
@{
characterKey: @"XC",
valueKey: @90
},
@{
characterKey: @"C",
valueKey: @100
},
@{
characterKey: @"CD",
valueKey: @400
},
@{
characterKey: @"D",
valueKey: @500
},
@{
characterKey: @"CM",
valueKey: @900
},
@{
characterKey: @"M",
valueKey: @1000
}
];
NSString* romanizedString = @"";
NSInteger remainder = self.integerValue;
for (NSInteger i = romanNumerals.count - 1; i >= 0; i--) {
NSDictionary* numeral = romanNumerals[i];
NSInteger value = ((NSNumber*)(numeral[valueKey])).integerValue;
NSUInteger timesFit = remainder / value;
if (timesFit > 0) {
romanizedString = [romanizedString
stringByAppendingString:[NSNumber
stringWithUnit:numeral[characterKey]
repeated:timesFit
]
];
remainder -= timesFit * value;
}
if (remainder <= 0) {
break;
}
}
return romanizedString;
}
+ (NSString*)stringWithUnit:(NSString*)unit repeated:(NSUInteger)repeatCount
{
NSString* repeatedString = @"";
for (NSUInteger i = 0; i < repeatCount; i++) {
repeatedString = [repeatedString stringByAppendingString:unit];
}
return repeatedString;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment