LeetCode12- 整数转罗马数字
生活随笔
收集整理的這篇文章主要介紹了
LeetCode12- 整数转罗马数字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
羅馬數字包含以下七種字符:?I,?V,?X,?L,C,D?和?M。
字符 數值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000例如, 羅馬數字 2 寫做?II?,即為兩個并列的 1。12 寫做?XII?,即為?X?+?II?。 27 寫做??XXVII, 即為?XX?+?V?+?II?。
通常情況下,羅馬數字中小的數字在大的數字的右邊。但也存在特例,例如 4 不寫做?IIII,而是?IV。數字 1 在數字 5 的左邊,所表示的數等于大數 5 減小數 1 得到的數值 4 。同樣地,數字 9 表示為?IX。這個特殊的規則只適用于以下六種情況:
- I?可以放在?V?(5) 和?X?(10) 的左邊,來表示 4 和 9。
- X?可以放在?L?(50) 和?C?(100) 的左邊,來表示 40 和?90。?
- C?可以放在?D?(500) 和?M?(1000) 的左邊,來表示?400 和?900。
給定一個整數,將其轉為羅馬數字。輸入確保在 1?到 3999 的范圍內。
示例?1:
輸入:?3 輸出: "III"示例?2:
輸入:?4 輸出: "IV"示例?3:
輸入:?9 輸出: "IX"示例?4:
輸入:?58 輸出: "LVIII" 解釋: L = 50, V = 5, III = 3.示例?5:
輸入:?1994 輸出: "MCMXCIV" 解釋: M = 1000, CM = 900, XC = 90, IV = 4.代碼:
class Solution {public String intToRoman(int num) {Map<Integer , String> map = new HashMap<>();map.put( 1 , "I" );map.put( 5 , "V" );map.put( 10 , "X" );map.put( 50 , "L" );map.put( 100 , "C" );map.put( 500 , "D" );map.put( 1000 , "M" );map.put( 4 , "IV" );map.put( 9 , "IX" );map.put( 40 , "XL" );map.put( 90 , "XC" );map.put( 400 , "CD" );map.put( 900 , "CM" );String s = "";if ( num < 1 || num > 3999 ) {return s;}int a[] = new int[4];//提取各位數字,從低位到最高位for ( int i = 0 ; i < 4 ; i++ ) {a[ i ] = num % 10;num /= 10;}for ( int i = a.length - 1 ; i >= 0 ; i-- ) {if ( a[i] == 0 ) {continue;}else if ( map.containsKey((int)(a[i] * Math.pow( 10 , (double)i))) ) {s += map.get( (int)(a[i] * Math.pow( 10 , (double)i)) );}else {if ( a[i] > 1 && a[i] < 4 ) {while ( a[i] >= 1 ) {s += map.get( (int)( Math.pow( 10 , (double)i)) );a[i]--;}}else {s += map.get( (int)( 5*Math.pow( 10 , (double)i)) );while( a[i] > 5 ) {s += map.get( (int)( Math.pow( 10 , (double)i)) );a[i]--;}}}}return s;} }代碼運行結果:
轉載于:https://www.cnblogs.com/cg-bestwishes/p/10681177.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的LeetCode12- 整数转罗马数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 物理、线性、虚拟、逻辑、有效地址
- 下一篇: Kubernetes基本概念之Name和