LeetCode 12 integer to roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999

与罗马字符转数字类似,注意按级处理。

string intToRoman(int num)
{
    string sRet;
    int iNum = num;

    while(iNum > 0)
    {
        if(iNum < 5)
        {
            if(iNum == 4)
            {
                sRet += "IV";
                break;
            }
            sRet += 'I';
            --iNum;
        }
        else if(5 <= iNum && iNum < 10)
        {
            if(iNum ==9)
            {
                sRet += "IX";
                break;
            }
            sRet += 'V';
            iNum -= 5;

        }
        else if(10 <= iNum && iNum < 50)
        {
            if(iNum >= 40)
            {
                sRet += "XL";
                iNum -= 40;
                continue;
            }
            sRet += 'X';
            iNum -= 10;
        }
        else if( 50 <= iNum && iNum < 90)
        {
            sRet += 'L';
            iNum -= 50;
        }
        else if(90 <= iNum && iNum < 500)
        {
            if(iNum < 100)
            {
                sRet += "XC";
                iNum -= 90;
                continue;
            }
            if(iNum >= 400)
            {
                sRet += "CD";
                iNum -= 400;
                continue;
            }
            sRet += "C";
            iNum -= 100;
        }
        else if( 500 <= iNum && iNum < 1000)
        {
            if(iNum >= 900)
            {
                sRet += "CM";
                iNum -= 900;
                continue;
            }
            sRet += "D";
            iNum -= 500;
        }
        else if( 1000 <= iNum)
        {
            sRet += "M";
            iNum -= 1000;
        }
    }
    return sRet;
}

略长的if else语句

posted @ 2015-04-22 22:10  BestWangJie  阅读(123)  评论(0编辑  收藏  举报