leetcode------Integer to Roman

标题: Integer to Roman
通过率: 34.4%
难度: 中等

Given an integer, convert it to a roman numeral.

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

前面做过数字转罗马数字,相对来说比较简单,从后面向前面走。本题是数字转罗马就是先看有几个1000,num/1000在看有几个一百,(num%1000)/100,在看有几个十,(num%100)/10,在看有几个个位数,num%10,然后对应的去查找数字表:

map={{"0","I","II","III","IV","V","VI","VII","VIII","IX"},{"0","X","XX","XXX","XL","L","LX"
,"LXX","LXXX","XC"},{"0","C","CC","CCC","CD","D",
"DC","DCC","DCCC","CM"},{"0","M","MM","MMM"}};

因为没有零,所以二维数组是从位置1开始的,具体看代码:

 1 public class Solution {
 2     public String intToRoman(int num) {
 3         String [][] map={{"0","I","II","III","IV","V","VI","VII","VIII","IX"},{"0","X","XX","XXX","XL","L","LX"
 4         ,"LXX","LXXX","XC"},{"0","C","CC","CCC","CD","D",
 5               "DC","DCC","DCCC","CM"},{"0","M","MM","MMM"}};
 6         String result="";
 7         if(num/1000!=0)result+=map[3][num/1000];
 8         if((num%1000)/100!=0)result+=map[2][(num%1000)/100];
 9         if((num%100)/10!=0)result+=map[1][(num%100)/10];
10         if(num%10!=0)result+=map[0][num%10];
11         return result;
12               
13     }
14 }

 python代码:

 1 class Solution:
 2     def intToRoman(self, num):
 3         numeral_map = {1: "I", 4: "IV", 5: "V", 9: "IX", 10: "X", 40: "XL", 50: "L", 90: "XC", 100: "C", 400: "CD", 500: "D", 900: "CM", 1000: "M"}
 4         keyset, length, result = sorted(numeral_map.keys()), len(numeral_map), ""
 5         while num > 0:
 6             for i in reversed(range(length)):
 7                 key = keyset[i]
 8                 while num / key > 0:
 9                     result += numeral_map[key]
10                     num -= key
11         return result

 

posted @ 2015-02-11 14:38  pku_smile  阅读(205)  评论(0编辑  收藏  举报