首先簡單介紹一下羅馬數字,一下摘自維基百科html
羅馬數字共有7個,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。按照下述的規則能夠表示任意正整數。須要注意的是羅馬數字中沒有「0」,與進位制無關。通常認爲羅馬數字只用來記數,而不做演算。app
Given a roman numeral, convert it to an integer.code
Input is guaranteed to be within the range from 1 to 3999.htm
3999範圍內的羅馬數字不會用到加上劃線的字母blog
從最後一個字符開始,若是當前字符對應的數字比上一個數字小,那麼就把結果減去當前字符對應的數字,不然加上當前字符對應數字。爲了處理邊界狀況,在原字符串最後添加一個字符,該字符是原來的尾字符。ip
class Solution { public: int romanToInt(string s) { int map[26]; map['I'-'A'] = 1; map['V'-'A'] = 5; map['X'-'A'] = 10; map['L'-'A'] = 50; map['C'-'A'] = 100; map['D'-'A'] = 500; map['M'-'A'] = 1000; int res = 0, n = s.size(); s.push_back(s[n-1]); for(int i = 0; i < n; i++) { if(map[s[i]-'A'] >= map[s[i+1]-'A']) res += map[s[i]-'A']; else res -= map[s[i]-'A']; } return res; } };
Integer to Romanleetcode
Given an integer, convert it to a roman numeral.字符串
Input is guaranteed to be within the range from 1 to 3999get
咱們注意到羅馬數字的字母是有規律的,能夠分紅幾組,I(1), V(5) 是一組, X(10), L(50)是一組, C(100), D(500)是一組, M(1000), d(應該是D加一個上劃線,表示5000) 是一組 ……。後一組的兩個數是前一組的10倍。string
對於大於10的整數,咱們把該整數逐位表示成羅馬數字。 本文地址
個位上的數字1~9的分別爲: I II III IV V VI VII VIII IX
十位上的數字1~9,只要把原來個位上的I 替換成 X, V 替換成L,X替換成C,即十位上的1~9表示的是10~90.
百位、千位以此類推。。。。。。
class Solution { public: string intToRoman(int num) { char romanChar[] = {'I','V','X','L','C','D','M'}; string res; int i = 6, factor = 1000; while(num != 0) { helper(num / factor, &romanChar[i], res); i -= 2; num %= factor; factor /= 10; } return res; } void helper(int k, char romanChar[], string &res) {// 0 <= k <= 9 if(k <= 0); else if(k <= 3) res.append(k, romanChar[0]); else if(k == 4) { res.push_back(romanChar[0]); res.push_back(romanChar[1]); } else if(k <= 8) { res.push_back(romanChar[1]); res.append(k-5, romanChar[0]); } else if(k == 9) { res.push_back(romanChar[0]); res.push_back(romanChar[2]); } } };
【版權聲明】轉載請註明出處:http://www.cnblogs.com/TenosDoIt/p/3793503.html