Leetcode: Roman to Integer

來源:互聯網
上載者:User

利用上一題的程式:

Judge Small: Accepted!

Judge Large:Time Limit Exceeded

map<string,int> romanmp;    void romanstr(string& roman, int num, char* symbol){if(num == 0)return;else if(num <= 3) roman.append(num, *symbol);else if(num == 4){roman.append(1,*symbol);roman.append(1,*(symbol+1));}else if(num <= 8){roman.append(1,*(symbol+1));roman.append(num-5,*symbol);}else if(num == 9){roman.append(1,*symbol);roman.append(1,*(symbol+2));}}string intToRoman(int num) {        // Start typing your C/C++ solution below        // DO NOT write int main() function            char symbol[9] = {'I','V','X','L','C','D','M'};        string roman="";int scale = 1000;int p=6;while(num){int bit = num/scale;romanstr(roman, bit, symbol+p);num = num%scale;scale /= 10;p -= 2;}return roman;    }int romanToInt(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        for(int i = 0;i <4000; i++)romanmp[intToRoman(i)] = i;return romanmp[s];    }

Accepted!

int romanToInt(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int length = s.length();    if(length <1) return 0;map<char,int> m;m['I'] = 1;m['V'] = 5;m['X'] = 10;m['L'] = 50;m['C'] = 100;m['D'] = 500;m['M'] = 1000;int i = length-1;int sum = m[s[i--]];while(i>=0)if(m[s[i+1]] > m[s[i]])sum -= m[s[i--]];elsesum += m[s[i--]];return sum;    }











相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.