[LeetCode] 012. Integer to Roman (Medium) (C++/Java/Python),leetcodepython

來源:互聯網
上載者:User

[LeetCode] 012. Integer to Roman (Medium) (C++/Java/Python),leetcodepython

索引:[LeetCode] Leetcode 題解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode

012.Integer_to_Roman (Medium)連結:

題目:https://oj.leetcode.com/problems/integer-to-roman/
代碼(github):https://github.com/illuz/leetcode

題意:

把十進位轉為羅馬數。

分析:

類比即可。

“羅馬數位基本符號有I(表示十進位數1),V(表示5),X(表示10),L(表示50),C(表示100),D(表示500),M(表示1000)。” – 羅馬數制(百度百科)

代碼:

C++:

class Solution {private:int val[13] = {1000, 900, 500, 400,100, 90, 50, 40,10, 9, 5, 4,1};string syb[13] = {"M", "CM", "D", "CD","C", "XC", "L", "XL","X", "IX", "V", "IV","I"};public:string intToRoman(int num) {string roman;int i = 0, k;while (num > 0) {k = num / val[i];while (k--) {roman += syb[i];num -= val[i];}i++;}return roman;}};


Java:

public class Solution {    private int[] val = {            1000, 900, 500, 400,            100, 90, 50, 40,            10, 9, 5, 4,            1    };    private String[] syb = new String[] {            "M", "CM", "D", "CD",            "C", "XC", "L", "XL",            "X", "IX", "V", "IV",            "I"    };    public String intToRoman(int num) {        StringBuilder roman = new StringBuilder();        int i = 0, k;        while (num > 0) {            k = num / val[i];            while (k-- > 0) {                roman.append(syb[i]);                num -= val[i];            }            i++;        }        return roman.toString();    }}


Python:

class Solution:    # @return a string    def intToRoman(self, num):        val = [            1000, 900, 500, 400,            100, 90, 50, 40,            10, 9, 5, 4,            1            ]        syb = [            "M", "CM", "D", "CD",            "C", "XC", "L", "XL",            "X", "IX", "V", "IV",            "I"            ]        roman = ''        i = 0        while  num > 0:            for _ in range(num // val[i]):                roman += syb[i]                num -= val[i]            i += 1        return roman


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.