Given an integer, convert it to a roman numeral. git
Input is guaranteed to be within the range from 1 to 3999. 數組
思路是把數字拆成單獨的部分,最後拼接起來 app
1. 拆分數字,求出每一位數字。 ui
2. 把每位數字單獨轉換singleDigitToRoman成羅馬數字,存入羅馬數字數組strSingleResult[i]中 spa
3. 最後拼接起來 code
單獨轉換方法singleDigitToRoman(int n, int nth)接收2個參數,一個是輸入數字,一個是當前數字的位數; blog
singleDigitToRoman方法中,把羅馬數字單個存放在char數組裏,方便調用; get
char singleRoman[] = {'I','V','X','L','C','D','M','#','#'}; // never use '#' string
數組中#都只是用來佔位的,避免數組越界;正常狀況下都不會出現。 it
根據輸入數字n,分段判斷;每段有不一樣的拼接方式。
#include <gtest/gtest.h> using namespace std; string singleDigitToRoman(int n, int nth) { if (n ==0) { return ""; } char singleRoman[] = {'I','V','X','L','C','D','M','#','#'}; // 1 5 10 50 100 500 1000 nth = 2*nth - 1; string strResult; if (n <= 3) { strResult.append(n,singleRoman[nth-1]); } else if (n == 4) { strResult.push_back(singleRoman[nth-1]); strResult.push_back(singleRoman[nth]); } else if (n == 5) { strResult.push_back(singleRoman[nth]); } else if (n >= 6 && n <= 8) { strResult.push_back(singleRoman[nth]); strResult.append(n-5,singleRoman[nth-1]); } else if (n == 9) { strResult.push_back(singleRoman[nth-1]); strResult.push_back(singleRoman[nth+1]); } else { strResult = "Error"; } return strResult; } string intToRoman(int num) { if (num < 1 || num > 3999) { return "Invalid Param!"; } string strSingleResult[4]; int index = 0; while (num) { strSingleResult[index] = singleDigitToRoman(num % 10, index + 1); num /= 10; ++index; } string strResult; while (index > 0) { strResult += strSingleResult[index-1]; --index; } return strResult; } TEST(Pratices, tIntToRoman) { //{'I','V','X','L','C','D','M','#','#'}; // 1 5 10 50 100 500 1000 // 1 ASSERT_EQ(intToRoman(1),"I"); // 99 ASSERT_EQ(intToRoman(99),"XCIX"); // 456 ASSERT_EQ(intToRoman(456),"CDLVI"); // 3999 ASSERT_EQ(intToRoman(3999),"MMMCMXCIX"); // 201 ASSERT_EQ(intToRoman(201),"CCI"); // 687 ASSERT_EQ(intToRoman(687),"DLLXXXVII"); }