LeetCode——Integer to Roman

來源:互聯網
上載者:User

標籤:leetcode

Given an integer, convert it to a roman numeral.

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

給定一個整數,把它轉換成羅馬數字。

輸入可以保證在1到3999之間。

是轉換規則。

1 2 3 4 5 6 7 8 9
I II III IV V VI VII VIII IX
                 
10 20 30 40 50 60 70 80 90
X XX XXX XL L LX LXX LXXX XC
                 
100 200 300 400 500 600 700 800 900
C CC CCC CD D DC DCC DCCC CM
下面的程式用的是窮舉,即把上面的表格用if else 寫了一遍。當然這課表也是有規律的,如1-3開頭的是重複,4-5截取後一個字元,6-8又是依次添一個尾字元。

public static String intToRoman(int num) {StringBuffer buf = new StringBuffer();int dddd = num / 1000;int ddd = num % 1000 / 100;int dd = num % 1000 % 100 / 10;int d = num % 1000 % 100 % 10;for(int i=0;i<dddd;i++)buf.append("M");if(ddd == 1)buf.append("C");else if(ddd == 2)buf.append("CC");else if(ddd == 3)buf.append("CCC");else if(ddd == 4)buf.append("CD");else if(ddd == 5)buf.append("D");else if(ddd == 6)buf.append("DC");else if(ddd == 7)buf.append("DCC");else if(ddd == 8)buf.append("DCCC");else if(ddd == 9)buf.append("CM");if(dd == 1)buf.append("X");else if(dd == 2)buf.append("XX");else if(dd == 3)buf.append("XXX");else if(dd == 4)buf.append("XL");else if(dd == 5)buf.append("L");else if(dd == 6)buf.append("LX");else if(dd == 7)buf.append("LXX");else if(dd == 8)buf.append("LXXX");else if(dd == 9)buf.append("XC");if(d == 1)buf.append("I");else if(d == 2)buf.append("II");else if(d == 3)buf.append("III");else if(d == 4)buf.append("IV");else if(d == 5)buf.append("V");else if(d == 6)buf.append("VI");else if(d == 7)buf.append("VII");else if(d == 8)buf.append("VIII");else if(d == 9)buf.append("IX");return buf.toString();}

整數和羅馬數位轉換規則見此 http://www.mathsisfun.com/roman-numerals.html 。

聯繫我們

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